// // SanViewController.m // Ifish // // Created by imac on 15/11/19. // Copyright © 2015年 imac. All rights reserved. // #import "ScanViewController.h" #import "QRCodeReaderView.h" #import #import #define widthRate kScreenSize.width/320 #import "ZBarReaderController.h" #import "CenterViewController.h" #import "LeftViewController.h" #import "ICSDrawerController.h" #import "RightViewController.h" #import "AFNetworking.h" #import "DeviceModel.h" #import "AppDelegate.h" #import "XuToCenterViewController.h" #import "IfishBlackListCenterViewController.h" #import "FourControlNormalCenterController.h" #import "IfishDataUnity.h" @interface ScanViewController () { QRCodeReaderView * readview;//二维码扫描对象 BOOL isFirst;//第一次进入该页面 BOOL isPush;//跳转到下一级页面 } @property (strong, nonatomic) CIDetector *detector; @property(nonatomic,strong) UIButton*bakbutton; @property(nonatomic,retain) NSTimer* getInfTimer ; @end @implementation ScanViewController - (void)viewDidLoad { [super viewDidLoad]; UILabel*labe=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)]; labe.text=@"扫描"; labe.textAlignment=NSTextAlignmentCenter; labe.textColor=[UIColor whiteColor]; self.navigationItem.titleView=labe; // self.title = @"扫描"; self.view.backgroundColor = [UIColor whiteColor]; // UIBarButtonItem * rbbItem = [[UIBarButtonItem alloc]initWithTitle:@"相册" style:UIBarButtonItemStyleDone target:self action:@selector(alumbBtnEvent)]; // self.navigationItem.rightBarButtonItem = rbbItem; // UIBarButtonItem * lbbItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(backButtonEvent)]; // self.navigationItem.leftBarButtonItem = lbbItem; [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"blackbar.png"] forBarMetrics:UIBarMetricsDefault]; _bakbutton = [UIButton buttonWithType:UIButtonTypeCustom]; _bakbutton.frame = CGRectMake(0, 0, 47,44); [_bakbutton setImage:[UIImage imageNamed:@"back_btn"] forState:UIControlStateNormal]; [_bakbutton addTarget: self action: @selector(backButtonEvent) forControlEvents: UIControlEventTouchUpInside]; UIBarButtonItem * lbbItem=[[UIBarButtonItem alloc]initWithCustomView:_bakbutton]; self.navigationItem.leftBarButtonItem=lbbItem; isFirst = YES; isPush = NO; [self InitScan]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark - 返回 - (void)backButtonEvent { [self dismissViewControllerAnimated:YES completion:^{ }]; } #pragma mark 初始化扫描 - (void)InitScan { //红线 // UIView*redview=[[UIView alloc]initWithFrame:CGRectMake(60*widthRate,kScreenSize.height/2, 200*widthRate, 1)]; // redview.backgroundColor=[UIColor redColor]; if (readview) { [readview removeFromSuperview]; readview = nil; } readview = [[QRCodeReaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height)]; readview.is_AnmotionFinished = YES; readview.backgroundColor = [UIColor clearColor]; readview.delegate = self; readview.alpha = 0; // [readview addSubview:redview]; [self.view addSubview:readview]; [UIView animateWithDuration:0.5 animations:^{ readview.alpha = 1; }completion:^(BOOL finished) { }]; } #pragma mark - 相册 - (void)alumbBtnEvent { self.detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }]; if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) { //判断设备是否支持相册 if (IFISHIOS8) { UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"未开启访问相册权限,现在去开启!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil]; alert.tag = 4; [alert show]; } else{ UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"设备不支持访问相册,请在设置->隐私->照片中进行设置!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; } return; } isPush = YES; UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init]; mediaUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //mediaUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum]; mediaUI.allowsEditing =YES; mediaUI.delegate = self; [self presentViewController:mediaUI animated:YES completion:^{ [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES]; }]; } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"]; readview.is_Anmotion = YES; [picker dismissViewControllerAnimated:YES completion:^{ [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES]; [self decodeImage:image]; //播放扫描二维码的声音 SystemSoundID soundID; NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:@"noticeMusic" ofType:@"wav"]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID); AudioServicesPlaySystemSound(soundID); // [self accordingQcode:scannedResult]; }]; } //MARK: - 解析照片 - (void)decodeImage:(UIImage *)image {//进行解码 ZBarSymbol *symbol = nil; ZBarReaderController* read = [ZBarReaderController new]; read.readerDelegate = self; CGImageRef cgImageRef = image.CGImage; for(symbol in [read scanImage:cgImageRef])break; // 将获得到条形码显示到我们的界面上 if (symbol!=nil) { NSLog(@"%@",symbol.data); [self accordingQcode:symbol.data]; //扫描结果处理 // [[LYQRCodeHandle shareHandle]readCodeResult:symbol.data fromSuperViewController:self]; } } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:^{ [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES]; }]; } #pragma mark -QRCodeReaderViewDelegate - (void)readerScanResult:(NSString *)result { readview.is_Anmotion = YES; [readview stop]; //播放扫描二维码的声音 SystemSoundID soundID; NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:@"noticeMusic" ofType:@"wav"]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID); AudioServicesPlaySystemSound(soundID); [self accordingQcode:result]; [self performSelector:@selector(reStartScan) withObject:nil afterDelay:1.5]; } #pragma mark - 扫描结果处理 - (void)accordingQcode:(NSString *)str { //iFishCamera:摄像头激活码标识 //deviceId= 水族箱设备标识 NSString*formatSting=[NSString stringWithFormat:@"%@",str]; NSString*headstring=[formatSting substringWithRange:NSMakeRange(0,9)]; NSString*deviceIdString=[str substringFromIndex:9]; if ([headstring isEqualToString:@"deviceId="]){ UserModel*model=[[DataCenter defaultDtacenter]valueForKey:@"UserLogIn"]; NSArray*arry=[[DataCenter defaultDtacenter]valueForKey:@"deviceInfo"]; NSMutableArray*deviceIdArr=[[NSMutableArray alloc]init]; DeviceModel*deviceModel=[[DeviceModel alloc]init]; if ([arry count]==0) { [self shareDeviceWithUserId:model.userId addDeviceId:deviceIdString]; }else{ for (deviceModel in arry) { NSString*string=[NSString stringWithFormat:@"%@",deviceModel.deviceId]; [deviceIdArr addObject:string]; } BOOL isExst=[deviceIdArr containsObject:deviceIdString]; if (isExst) { [self.view makeToast:@"设备已经存在"]; [self dismissViewControllerAnimated:YES completion:^{ }]; }else{ [self shareDeviceWithUserId:model.userId addDeviceId:deviceIdString]; } } }else{ if ([str hasPrefix:@"iFishCamera:"]) { //摄像头验证码 激活摄像头用 NSString *cameraCade=[str substringFromIndex:12]; if (!self.cameraModel){ [self.view makeToast:@"请到首页摄像头列表,选择摄像头后激活"]; return; } [self activeCameraWith:self.cameraModel.cameraId addWith:cameraCade]; }else if ([str hasPrefix:@"IfishShopId:"]){ //扫描店铺二维码 //成为店铺会员 NSString *shopId=[str substringFromIndex:12]; [self addShopsUser:shopId]; }else{ NSString *result = [NSString stringWithFormat:@"扫面结果:%@",str]; [self.view makeToast:result]; } } } #pragma mark - 扫一扫 绑定水族箱 //老版本扫一扫 绑定 接口中无请求头 已换新接口 -(void)shareDeviceWithUserId:(NSNumber*)userId addDeviceId:(NSString*)deviceId{ NSString *userID =[NSString stringWithFormat:@"%@",userId]; [AFHttpTool shareDeviceWhth:userID deviceId:deviceId success:^(id response) { NSDictionary*resultDic=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; NSLog(@"result:%@",resultDic[@"result"]); if ([resultDic[@"result"] isEqualToString:@"100"]) { NSMutableArray*deviceArry=[[DataCenter defaultDtacenter]valueForKey:@"deviceInfo"]; [[IfishDataUnity shareDataInstance] addDeviceByQRCodeWithDic:resultDic addWith:deviceArry dismiss:self]; }else if ([resultDic[@"result"] isEqualToString:@"101"]){ [self.view makeToast:@"分享失败"]; }else if ([resultDic[@"result"] isEqualToString:@"301"]){ [self.view makeToast:@"请求验证失败,请重新登陆"]; }else if ([resultDic[@"result"] isEqualToString:@"302"]){ [self.view makeToast:@"请求被舍弃,未执行"]; } } failure:^(NSError *err) { }]; } - (void)reStartScan { readview.is_Anmotion = NO; if (readview.is_AnmotionFinished) { [readview loopDrawLine]; } [readview start]; } #pragma mark - view - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (isFirst || isPush) { if (readview) { [self reStartScan]; } } } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; if (readview) { [readview stop]; readview.is_Anmotion = YES; } } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; if (isFirst) { isFirst = NO; } if (isPush) { isPush = NO; } } #pragma mark - 激活摄像头 -(void)activeCameraWith:(NSString *)cameraId addWith:(NSString *)activeCode{ AFHTTPRequestOperationManager*mannager=[AFHTTPRequestOperationManager manager]; mannager.responseSerializer=[AFHTTPResponseSerializer serializer]; NSMutableDictionary * para = [NSMutableDictionary dictionary]; [para setValue:cameraId forKey:@"cameraId"]; [para setValue:activeCode forKey:@"activeCode"]; [mannager POST:JiHuoSheXiangTou parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) { NSDictionary*resultDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSLog(@"result:%@",resultDic[@"result"]); if ([resultDic[@"result"] isEqualToString:@"100"]) { [self.view makeToast:@"激活成功"]; NSMutableArray *oldCameraArr= [[DataCenter defaultDtacenter]valueForKey:@"cameraArr"]; NSMutableArray *newCamerArr =[[NSMutableArray alloc] init]; for (IfishCameraModel *camera in oldCameraArr) { if ([camera.cameraId isEqualToString:cameraId]) { camera.isActive = @"1"; } [newCamerArr addObject:camera]; } //存储摄像头数组 [[DataCenter defaultDtacenter]setValue: newCamerArr forKey:@"cameraArr"]; _getInfTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scanviewDelayDissMiss) userInfo:nil repeats:NO]; ; }else if ([resultDic[@"result"] isEqualToString:@"101"]){ [self.view makeToast:@"激活失败"]; }else if ([resultDic[@"result"] isEqualToString:@"208"]){ [self.view makeToast:@"激活码已被使用"]; }else if ([resultDic[@"result"] isEqualToString:@"209"]){ [self.view makeToast:@"无效的激活码"]; }else{ } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { }]; } -(void)scanviewDelayDissMiss{ [_getInfTimer invalidate]; _getInfTimer = nil; // __weak typeof (self) weakslef = self; [self dismissViewControllerAnimated:YES completion:^{ }]; } #pragma mark -成为商家会员 -(void)addShopsUser:(NSString *)shopId{ NSString *useriD =[dataContorl dataControlGetUserIdInfo]; [AFHttpTool becomeShopUserWith:useriD shopId:shopId success:^(id response) { NSDictionary*resultDic=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; NSLog(@"result:%@",resultDic[@"result"]); if ([resultDic[@"result"] isEqualToString:@"100"]) { [[UIApplication sharedApplication].keyWindow makeToast:@"恭喜已成为该商家会员"]; [self dismissViewControllerAnimated:YES completion:^{ }]; }else{ NSString *str = [NSString stringWithFormat:@"请求出错:%@",resultDic[@"result"]]; [self.view makeToast:str]; } } failure:^(NSError *err) { [self.view makeToast:@"请求异常"]; }]; } //设置根视图 -(void)setAppTabRoot{ IfishMianTabViewController *mianVC=[[IfishMianTabViewController alloc] init]; [UIApplication sharedApplication].delegate.window.rootViewController=mianVC; } @end