// // ScanVC.m // jiaPei // // Created by apple on 16/4/19. // Copyright © 2016年 JCZ. All rights reserved. // #import "ScanVC.h" #import "CDZQRScanView.h" #import "ScanResultVC.h" #import "MyWebViewVC.h" #import #import "DES3Util.h" #import //引入定位功能所有的头文件(新) #import "AFNetworking.h" #import #define KWidth (kSize.width/2.0 + 30) typedef NS_ENUM(NSInteger, ScanType) { //惠智/多伦等模拟设备登录 Huizhi_mn, //兴中正模拟设备登录 Xzz_mn }; @interface ScanVC () { //闪光灯 UIView *flashlightView; UILabel *flashlightStateLabel; UIButton *flashlightBtn; //扫描结果 NSString *dataString; //扫码类型 ScanType locationType; //地图定位 CLLocationCoordinate2D myCoordinate; } @property (nonatomic ,strong) CDZQRScanView *scanView; @property (nonatomic ,strong) UIImagePickerController *imagePicker; //扫码区域上方提示文字 @property (nonatomic, strong) UILabel *topTitle; #pragma mark - 底部几个功能:开启闪光灯、相册、我的二维码 //底部显示的功能项 @property (nonatomic, strong) UIView *bottomItemsView; //相册 @property (nonatomic, strong) UIButton *btnPhoto; //闪光灯 @property (nonatomic, strong) UIButton *btnFlash; //闪关灯开启状态记录 @property(nonatomic,assign)BOOL isOpenFlash; @end @implementation ScanVC - (void)viewDidLoad { [super viewDidLoad]; //vc的基本设置 self.view.backgroundColor = [UIColor blackColor]; self.title = @"二维码扫描"; [self configNavigationBar]; // [self.view addSubview:self.scanView]; // [self drawTitle]; // [self drawBottomItems]; [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { }]; UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings]; BOOL isEnable = (UIUserNotificationTypeNone == setting.types) ? NO : YES; if (!isEnable) { [RQ_SHARE_FUNCTION showAlertWithTitle:@"温馨提示" message:@"打开APP推送功能,能够更及时的进行计时过程验证哦!!!" alertControllerStyle:UIAlertControllerStyleAlert cancelButtonTitle:@"不打开" otherButtonTitles:@[@"打开推送"] otherButtonStyles:nil completion:^(NSUInteger selectedOtherButtonIndex) { if (selectedOtherButtonIndex == 0) { UIApplication *application = [UIApplication sharedApplication]; NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if ([application canOpenURL:url]) { if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) { [application openURL:url options:@{} completionHandler:nil]; } else { [application openURL:url]; } } } }]; } } - (void)changeFlash { [self.scanView changeTorch]; self.isOpenFlash = !self.isOpenFlash; if (self.isOpenFlash) { [_btnFlash setImage:[UIImage imageNamed:@"qrcode_scan_btn_flash_down"] forState:UIControlStateNormal]; } else { [_btnFlash setImage:[UIImage imageNamed:@"qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal]; } } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.scanView.delegate = self; [self.scanView startScanning]; } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.scanView stopScanning]; self.scanView.delegate = nil; } -(void)scanBlock:(MyBlockType)block { scanBlock = block; } #pragma mark - 绘制扫描区域 - (void)drawTitle { if (!_topTitle) { CGRect scanRect = self.scanView.scanRect; self.topTitle = [[UILabel alloc]init]; _topTitle.bounds = CGRectMake(0, 0, scanRect.size.width*2/3, 0); _topTitle.font = [UIFont systemFontOfSize:15]; _topTitle.textAlignment = NSTextAlignmentCenter; _topTitle.numberOfLines = 0; _topTitle.text = @"将取景框对准二维码即可自动扫描"; _topTitle.textColor = [UIColor whiteColor]; [_topTitle sizeToFit]; _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, CGRectGetMinY(scanRect)-_topTitle.height/2-15); [self.view addSubview:_topTitle]; } } - (void)drawBottomItems { if (_bottomItemsView) { return; } CGFloat bottomBarH = 100; self.bottomItemsView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view.frame)-bottomBarH-kNavOffSet-kSafeAreaBottomHeight, CGRectGetWidth(self.view.frame), bottomBarH+kSafeAreaBottomHeight)]; _bottomItemsView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6]; [self.view addSubview:_bottomItemsView]; CGSize size = CGSizeMake(65, 87); self.btnFlash = [[UIButton alloc]init]; _btnFlash.bounds = CGRectMake(0, 0, size.width, size.height); _btnFlash.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)/2, bottomBarH/2); [_btnFlash setImage:[UIImage imageNamed:@"qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal]; [_btnFlash addTarget:self action:@selector(changeFlash) forControlEvents:UIControlEventTouchUpInside]; self.btnPhoto = [[UIButton alloc]init]; _btnPhoto.bounds = _btnFlash.bounds; _btnPhoto.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)*2/3, bottomBarH/2); [_btnPhoto setImage:[UIImage imageNamed:@"qrcode_scan_btn_photo_nor"] forState:UIControlStateNormal]; [_btnPhoto setImage:[UIImage imageNamed:@"qrcode_scan_btn_photo_down"] forState:UIControlStateHighlighted]; [_btnPhoto addTarget:self action:@selector(openLibary) forControlEvents:UIControlEventTouchUpInside]; [_bottomItemsView addSubview:_btnFlash]; // [_bottomItemsView addSubview:_btnPhoto]; } #pragma mark - imagePickerDelegate - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary *)info{ [picker dismissViewControllerAnimated:YES completion:nil]; UIImage *image = info[UIImagePickerControllerOriginalImage]; NSString *result = [self messageFromQRCodeImage:image]; if (result.length == 0) { [self showAlert:@"未识别到二维码"]; return; } [self showAlert:result]; } #pragma mark - 扫描结果 scanViewDelegate - (void)scanView:(CDZQRScanView *)scanView pickUpMessage:(NSString *)message { [scanView stopScanning]; if ([message containsString:@"#DECODE#"] && message.length > 8) { //程序内某些验证 NSString *testString = [DES3Util decrypt:[message substringFromIndex:8]]; NSLog(@"\n原完整内容: %@ \n解密后: #DECODE#%@",message,testString); if (testString == nil) { [self showResultString:@"二维码内容格式错误(#DECODE#+异常字符串)" title:nil]; return; } //集中理论计时签到/签退 if ([testString containsString:@"#LNJP#theory"]) { if ([_type isEqualToString:@"2"]) { [self showResultString:@"二维码类型错误,请扫描\"模拟设备登录\"二维码" title:@"模拟设备登录"]; return; } NSArray *array = [testString componentsSeparatedByString:@"@@"]; testString = [testString substringFromIndex:6]; NSDictionary *dic = @{@"scanType":[array lastObject],@"dataString":[DES3Util encrypt:testString]}; if (scanBlock) { [self.navigationController popViewControllerAnimated:YES]; scanBlock(dic); } return; } //模拟终端登录 #DECODE#LNJP#simulatorLogin@@132456@@BFEBFBFF000206A7 if ([testString containsString:@"#LNJP#simulatorLogin"]) { [Tools confirmImeiWithLogType:@"3" successBlock:^{ dataString = testString; if (scanBlock) { if ([self.type isEqualToString:@"2"]) {//来自模拟vc locationType = Xzz_mn; [self getMyLocation]; }else if ([self.type isEqualToString:@"1"]){//来自homebase locationType = Xzz_mn; [self getMyLocation]; }else{ [self showResultString:@"二维码类型错误" title:nil]; } } }]; return; } //惠智模拟计时 #LNJP#huizhi@@BFEBFBFF000206A7@@1530258491165 //多伦 if ([testString containsString:@"#LNJP#huizhi"] || [testString containsString:@"#LNJP#other"]) { dataString = testString; locationType = Huizhi_mn; [self getMyLocation]; return; } [self showResultString:message title:@"扫描结果"]; return; } if([self.type isEqualToString:@"2"]){ [self showResultString:@"二维码类型错误,请扫描\"模拟设备登录\"二维码" title:@"模拟设备登录"]; return; } //进某网址 if ([self.type isEqualToString:@"1"]) { if ([message hasPrefix:@"http://"] || [message hasPrefix:@"https://"]) { MyWebViewVC *vc = [MyWebViewVC new]; vc.urlString = message; NSArray *vcs = self.navigationController.childViewControllers; NSMutableArray *arr = [NSMutableArray arrayWithArray:vcs]; [arr replaceObjectAtIndex:vcs.count-1 withObject:vc]; [self.navigationController setViewControllers:arr animated:YES]; return; } [self showResultString:message title:@"扫描结果"]; } } #pragma mark - 打开相册 - (void)openLibary{ if (![self isLibaryAuthStatusCorrect]) { [self showAlert:@"需要相册权限"]; return; } [self presentViewController:self.imagePicker animated:YES completion:nil]; } - (NSString *)messageFromQRCodeImage:(UIImage *)image{ if (!image) { return nil; } CIContext *context = [CIContext contextWithOptions:nil]; CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}]; CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage]; NSArray *features = [detector featuresInImage:ciImage]; if (features.count == 0) { return nil; } CIQRCodeFeature *feature = features.firstObject; return feature.messageString; } - (BOOL)isLibaryAuthStatusCorrect{ PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus]; if (authStatus == PHAuthorizationStatusNotDetermined || authStatus == PHAuthorizationStatusAuthorized) { return YES; } return NO; } #pragma mark - 定位 -(void)getMyLocation{ BOOL isOpenTwo = [defUser.userDict[@"mnqTwoOpen"] isEqualToString:@"0"]; BOOL isOpenThree = [defUser.userDict[@"mnqThreeOpen"] isEqualToString:@"0"]; if (isOpenThree && isOpenTwo) { showMsgByAlert(self, @"暂未开启模拟计时"); return; } //开启百度定位 DistanceFilter:将被通知任何移动(若=10,表示超出10米才会回调位置信息) [[MapManager sharedManager] updateLocationWithDistanceFilter:1 CompleteBlock:^(BOOL success, CLLocation * _Nonnull location) { if (success) { self->myCoordinate = location.coordinate; if (self->locationType == Xzz_mn) { [self MNQLogin]; }else if(self->locationType == Huizhi_mn){ [self HuiZhiMNQLogin]; } } }]; } #pragma mark - 模拟设备登录 - (void)MNQLogin{ //dataString #LNJP#simulatorLogin @@ BFEBFBFF000206A7 NSArray *arr = [dataString componentsSeparatedByString:@"@@"]; NSString *account = defUser.userDict[@"loginCode"]; NSString *urlStr = [NSString stringWithFormat:@"%@lnmn/admin/phoneLogin",@"http://122.lnjppt.com/"];//@"http://192.168.1.237:8083/" NSMutableString *paramStr = [NSMutableString new]; [paramStr appendString:[NSString stringWithFormat:@"%@",account]];//uname [paramStr appendString:[NSString stringWithFormat:@";%@",arr[1]]];//mnqSn [paramStr appendString:[NSString stringWithFormat:@";%@",defUser.userDict[@"city"]]];//dqbh [paramStr appendString:[NSString stringWithFormat:@";%f",myCoordinate.longitude]];//lng [paramStr appendString:[NSString stringWithFormat:@";%f",myCoordinate.latitude]];//lat //设置请求管理器 AFHTTPSessionManager *afSessionManager = [AFHTTPSessionManager manager]; afSessionManager.requestSerializer = [AFJSONRequestSerializer serializer]; afSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; afSessionManager.responseSerializer.acceptableContentTypes = [afSessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"]; afSessionManager.requestSerializer.timeoutInterval = 15; NSLog(@"%@",urlStr); [MBProgressHUD showMessage:@"正在登录模拟设备" toView:self.view]; [afSessionManager POST:urlStr parameters:@{@"params":[DES3Util encrypt:paramStr]} headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //请求成功 [MBProgressHUD hideHUDForView:self.view]; if (responseObject == nil) { [self showResultString:@"服务异常:无数据返回" title:@"登录失败"]; return; } NSDictionary *root = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; /* code=0—登录成功 code=1—用户不存在 code=2—未绑定报名信息 code=3—当前培训阶段无法参与模拟训练 code=4—当前模拟设备未绑定 code=5—该设备已有学员在训练中 code=6—模拟教室信息不存在 code=7—您当前不在模拟教室有效范围内 */ if (![root[@"code"] isEqualToString:@"0"]) { [self showResultString:root[@"msg"] title:@"登录失败"]; return; } //A 在 码I 计时; B 在 码II 计时; C 未计时,码III 未计时 /* C扫码I/II,服务器返回code=1; A扫码I,服务器返回code=0; */ NSLog(@"模拟设备登录成功123---urlString---><>%@,\n%@",urlStr,root); if ([self.type isEqualToString:@"2"]) {//function个人界面 [self.navigationController popViewControllerAnimated:NO]; if (scanBlock) { scanBlock(@"success"); } }else if([self.type isEqualToString:@"1"]){//如果是homebase进来的 [self.navigationController popViewControllerAnimated:NO]; if (scanBlock) { scanBlock(@{@"scanType":@"MNQTrain"}); } } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"请求失败123----><>%@",error); [MBProgressHUD hideHUDForView:self.view]; NSString *reason = @"请求失败"; if ([error.localizedDescription isEqualToString:@"The request timed out."]) { //,@"请求超时" reason = @"连接超时,请检查手机网络"; } [self showResultString:reason title:@"登录失败"]; }]; } #pragma mark - 惠智模拟设备登录 - (void)HuiZhiMNQLogin{ //dataString #LNJP#simulatorLogin @@ BFEBFBFF000206A7 @@ 时间戳 NSArray *arr = [dataString componentsSeparatedByString:@"@@"]; NSString *account = defUser.userDict[@"loginCode"]; NSString *urlStr = [NSString stringWithFormat:@"%@appservice/lnsimulator/phoneLogin",@"http://app.lnjppt.com/"];//@"http://218.85.55.253:9091/ln" @"http://192.168.1.3:8081/ln" NSMutableString *paramStr = [NSMutableString new]; // [paramStr appendString:arr[1]];//uuid [paramStr appendString:[NSString stringWithFormat:@"%@",account]];//uname [paramStr appendString:[NSString stringWithFormat:@";%@",arr[1]]];//mnqSn [paramStr appendString:[NSString stringWithFormat:@";%@",defUser.userDict[@"city"]]];//dqbh [paramStr appendString:[NSString stringWithFormat:@";%f",myCoordinate.longitude]];//lng [paramStr appendString:[NSString stringWithFormat:@";%f",myCoordinate.latitude]];//lat [paramStr appendString:[NSString stringWithFormat:@";%@",arr[2]]]; // NSTimeInterval timeI = [[NSDate date] timeIntervalSince1970] * 1000; // [paramStr appendString:[NSString stringWithFormat:@";%.0f",timeI]]; //设置请求管理器 AFHTTPSessionManager *afSessionManager = [AFHTTPSessionManager manager]; afSessionManager.requestSerializer = [AFJSONRequestSerializer serializer]; afSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; afSessionManager.responseSerializer.acceptableContentTypes = [afSessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"]; afSessionManager.requestSerializer.timeoutInterval = 15; NSLog(@"%@ \n params:{%@}",urlStr,paramStr); [MBProgressHUD showMessage:@"正在登录模拟设备" toView:self.view]; [afSessionManager POST:urlStr parameters:@{@"params":[DES3Util encrypt:paramStr]} headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //请求成功 [MBProgressHUD hideHUDForView:self.view]; if (responseObject == nil) { [self showResultString:@"服务异常:无数据返回" title:@"登录失败"]; return; } NSDictionary *root = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSLog(@"惠智/多伦:%@---->: %@",urlStr,root); if ([root[@"code"] isEqualToString:@"90"]) { UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:root[@"msg"] preferredStyle:UIAlertControllerStyleAlert]; [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { [LoginViewController loginFromVC:self]; }]]; [self presentViewController:alertFind animated:true completion:nil]; return; } if (![root[@"code"] isEqualToString:@"0"]) { [self showResultString:root[@"msg"] title:@"登录失败"]; return; } NSString *carNum = nil; NSDictionary *body = root[@"body"]; if (body && [body isKindOfClass:[NSDictionary class]]) { NSDictionary *map = body[@"map"]; if (map && [map isKindOfClass:[NSDictionary class]]) { carNum = [NSString stringWithFormat:@"%@",map[@"carnum"]]; } } NSString *successStr = @"模拟设备已登录"; if (carNum && carNum.length != 0) { successStr = [NSString stringWithFormat:@"%@,欢迎您!\n已成功登录模拟设备【%@】,祝您体验愉快",defUser.userName,carNum]; } [self showResultString:successStr title:@"登录成功"]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"请求失败123----><>%@",error); [MBProgressHUD hideHUDForView:self.view]; NSString *reason = @"请求失败"; if ([error.localizedDescription isEqualToString:@"The request timed out."]) { //,@"请求超时" reason = @"连接超时,请检查手机网络"; } [self showResultString:reason title:@"登录失败"]; }]; } #pragma mark - alert 提示 -(void)showResultString:(NSString *)str title:(NSString *)title{ ScanResultVC *vc = [ScanResultVC new]; vc.resultStr = str; vc.navigationItem.title = title; if (self == nil) {//请求网络数据到一半,返回首页 return; } NSArray *vcs = self.navigationController.childViewControllers; NSMutableArray *arr = [NSMutableArray arrayWithArray:vcs]; if (vcs.count > 1) { [arr replaceObjectAtIndex:vcs.count-1 withObject:vc]; }else { [arr addObject:vc]; } [self.navigationController setViewControllers:arr animated:YES]; } - (void)showAlert:(NSString *)message { UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]; [alert addAction:cancelAction]; [self presentViewController:alert animated:YES completion:nil]; } #pragma mark - get - (CDZQRScanView *)scanView{ if (!_scanView) { _scanView = [[CDZQRScanView alloc]initWithFrame:CGRectMake(0, 0, kSize.width, kSize.height-kNavOffSet-kSafeAreaBottomHeight)]; _scanView.delegate = self; _scanView.showBorderLine = YES; _scanView.scanLineColor = [UIColor cyanColor]; _scanView.cornerLineColor = [UIColor whiteColor]; // CGSize scanSize = CGSizeMake(_scanView.width * 2/3, _scanView.width * 2/3); // _scanView.scanRect = CGRectMake((_scanView.size.width - scanSize.width)/2, (_scanView.size.height - 100 - scanSize.height)/2, scanSize.width, scanSize.height); } return _scanView; } - (UIImagePickerController *)imagePicker{ if (!_imagePicker) { _imagePicker = [[UIImagePickerController alloc]init]; _imagePicker.delegate = self; _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; } return _imagePicker; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end