ScanToLoginViewController.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. //
  2. // QRCodeScanViewController.m
  3. // 隐私保护
  4. //
  5. // Created by APPLE on 2023/9/19.
  6. //
  7. #import "ScanToLoginViewController.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. #import <ImageIO/ImageIO.h>
  10. #import "RSATool.h"
  11. #import <TZImageManager.h>
  12. #import <TZImagePickerController.h>
  13. @interface ScanToLoginViewController ()<AVCaptureMetadataOutputObjectsDelegate,AVCaptureVideoDataOutputSampleBufferDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
  14. @property(nonatomic,strong)AVCaptureVideoPreviewLayer *layer;
  15. //捕捉会话
  16. @property(nonatomic,strong)AVCaptureSession *session;
  17. //辅助区域框
  18. @property(nonatomic,strong)UIImageView * cyanEdgeImageView;
  19. @property(nonatomic,strong)UIImageView * qrCodeScanLine;
  20. @property(nonatomic,strong)NSTimer * scanLineTimer;
  21. ////打开灯光btn,默认为hidden
  22. //
  23. //@property(nonatomic,strong)UIButton * lightBtn;
  24. //
  25. ////获取相册图片进行扫描
  26. //
  27. //@property(nonatomic,strong)UIButton * photoBtn;
  28. @end
  29. @implementation ScanToLoginViewController
  30. - (void)viewDidLoad {
  31. [super viewDidLoad];
  32. // Do any additional setup after loading the view.
  33. [self.navigationBar setHidden:YES];
  34. [self.toolBar setHidden:YES];
  35. AVAuthorizationStatus authStatus =[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  36. //判断摄像头状态是否可用
  37. if(authStatus==AVAuthorizationStatusAuthorized){
  38. [self startScan];
  39. }else{
  40. NSLog(@"未开启相机权限,请前往设置中开启");
  41. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  42. dispatch_async(dispatch_get_main_queue(), ^{
  43. if (granted) {
  44. // 用户同意授权
  45. [self startScan];;
  46. } else {
  47. // 用户拒绝授权
  48. [self showPermissionDeniedAlert];
  49. }
  50. });
  51. }];
  52. }
  53. }
  54. - (void)showPermissionDeniedAlert {
  55. NSString * titleStr = NSLocalizedString(@"Camera_permissions_disabled",nil);
  56. NSString * tipStr = NSLocalizedString(@"Camera_permissions_open_tip",nil);
  57. UIAlertController *alert = [UIAlertController alertControllerWithTitle:titleStr
  58. message:tipStr
  59. preferredStyle:UIAlertControllerStyleAlert];
  60. NSString* cancelStr = NSLocalizedString(@"other_cancel",nil);
  61. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  62. [self backBtnPressed];
  63. }];
  64. NSString*settingStr = NSLocalizedString(@"set_Privacy_button_title",nil);
  65. UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:settingStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  66. [self backBtnPressed];
  67. // 跳转到应用设置页面
  68. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  69. if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
  70. [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
  71. }
  72. }];
  73. [alert addAction:cancelAction];
  74. [alert addAction:settingsAction];
  75. [self presentViewController:alert animated:YES completion:nil];
  76. }
  77. -(void)viewWillDisappear:(BOOL)animated
  78. {
  79. [super viewWillDisappear:animated];
  80. if(_scanLineTimer)[_scanLineTimer invalidate];
  81. }
  82. //开始扫描二维码
  83. -(void)startScan{
  84. //1.创建捕捉会话,AVCaptureSession是第一个要被创建的对象,所有的操作都要基于这一个session
  85. self.session = [[AVCaptureSession alloc]init];
  86. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  87. AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
  88. [self.session addInput:input];
  89. //3.添加输出数据(示例对象-->类对象-->元类对象-->根元类对象)
  90. /*输入的类是AVCaptureInput,那么输出的类相应的就应该是AVCaptureOutput。
  91.  输出不需要和设备挂钩,因为一般情况下,我们的输出要么是音频或视频文件,要么是一些其他的数据,像二维码扫描一般是字符串类型。
  92.  所以创建AVCaptureOutput实例就不需要AVCaptureDevice对象。
  93.  AVCaptureOutput也同样是一个抽象类,同样要使用其子类,在这里我们扫描二维码,
  94.  使用的是AVCaptureMetadataOutput,设置代码如下所示*/
  95. AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
  96. [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  97. //设置能扫描的区域,这里注意,CGRectMake的x,y和width,height的值是互换位置
  98. output.rectOfInterest=CGRectMake(250/self.view.frame.size.height, 100/self.view.frame.size.width, (self.view.frame.size.width-200)/self.view.frame.size.width, (self.view.frame.size.width-200)/self.view.frame.size.width);
  99. [self.session addOutput:output];
  100. //设置输入元数据的类型(类型是二维码,条形码数据,注意,这个一定要写在添加到session后面,不然要崩溃,如果只需要扫描二维码只需要AVMetadataObjectTypeQRCode,如果还需要扫描条形码,那么全部添加上)
  101. [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,
  102. AVMetadataObjectTypeEAN8Code,
  103. AVMetadataObjectTypeEAN13Code,
  104. AVMetadataObjectTypeCode39Code,
  105. AVMetadataObjectTypeCode39Mod43Code,
  106. AVMetadataObjectTypeCode93Code,
  107. AVMetadataObjectTypeCode128Code,
  108. AVMetadataObjectTypePDF417Code,
  109. AVMetadataObjectTypeAztecCode,
  110. AVMetadataObjectTypeUPCECode,
  111. AVMetadataObjectTypeInterleaved2of5Code,
  112. AVMetadataObjectTypeITF14Code,
  113. AVMetadataObjectTypeDataMatrixCode,
  114. ]];
  115. //4.添加扫描图层
  116. self.layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
  117. self.layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
  118. self.layer.frame = self.view.bounds;
  119. [self.view.layer addSublayer:self.layer];
  120. //5.创建view,通过layer层进行设置边框宽度和颜色,用来辅助展示扫描的区域
  121. _cyanEdgeImageView=[[UIImageView alloc] initWithFrame:CGRectMake(100, 250, self.view.frame.size.width-200, self.view.frame.size.width-200)];
  122. // _cyanEdgeImageView.layer.borderWidth=2;
  123. //
  124. // _cyanEdgeImageView.layer.borderColor =[UIColor cyanColor].CGColor;
  125. _cyanEdgeImageView.image = [UIImage imageNamed:@"qrCode_scan_bg"];
  126. [self.view addSubview:_cyanEdgeImageView];
  127. _qrCodeScanLine=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-200, 1)];
  128. _qrCodeScanLine.image = [UIImage imageNamed:@"qrCode_scan_line"];
  129. [_cyanEdgeImageView addSubview:_qrCodeScanLine];
  130. _scanLineTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(scanLineDownAndUpFun) userInfo:nil repeats:YES];
  131. UILabel *tipLib = [[UILabel alloc] initWithFrame:CGRectMake(20, _cyanEdgeImageView.hw_max_y + 15, SCREEN_W - 40, 20)];
  132. tipLib.text = NSLocalizedString(@"guide_qrcoede_tips_please",nil);
  133. tipLib.font = [UIFont systemFontOfSize:14.0];
  134. tipLib.textAlignment = NSTextAlignmentCenter;
  135. tipLib.textColor = [UIColor whiteColor];
  136. [self.view addSubview:tipLib];
  137. //6.创建检测光感源
  138. AVCaptureVideoDataOutput *guangOutPut = [[AVCaptureVideoDataOutput alloc] init];
  139. [guangOutPut setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
  140. //设置为高质量采集率
  141. [self.session setSessionPreset:AVCaptureSessionPresetHigh];
  142. //把光感源添加到会话
  143. [self.session addOutput:guangOutPut];
  144. // self.lightBtn=[[UIButton alloc]initWithFrame:CGRectMake(150, cyanView.frame.origin.y+cyanView.frame.size.height+100, self.view.frame.size.width-300, self.view.frame.size.width-300)];
  145. //
  146. // self.lightBtn.backgroundColor=[UIColor grayColor];
  147. //
  148. // [self.lightBtn addTarget:self action:@selector(lightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  149. //
  150. //打开相册
  151. UIButton *openAlbunBut = [[UIButton alloc] init];
  152. [openAlbunBut setTitle:NSLocalizedString(@"guide_qrcoede_open_album",nil) forState:UIControlStateNormal];
  153. [openAlbunBut setTitleColor:[UIColor hwColor:@"#3B7FFF" alpha:1.0] forState:UIControlStateNormal];
  154. openAlbunBut.titleLabel.font = [UIFont systemFontOfSize:14.0];
  155. [openAlbunBut addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  156. openAlbunBut.backgroundColor = [UIColor hwColor:@"#FFFFFF" alpha:0.2];
  157. [self.view addSubview:openAlbunBut];
  158. openAlbunBut.layer.cornerRadius = 24;
  159. openAlbunBut.layer.masksToBounds = YES;
  160. [openAlbunBut mas_makeConstraints:^(MASConstraintMaker *make) {
  161. make.width.mas_equalTo(140);
  162. make.height.mas_equalTo(48);
  163. make.centerX.mas_equalTo(0);
  164. make.bottom.mas_equalTo(-80);
  165. }];
  166. // [self.view addSubview:self.lightBtn];
  167. // self.photoBtn=[[UIButton alloc]initWithFrame:CGRectMake(100, self.lightBtn.frame.origin.y+self.lightBtn.frame.size.height+50, self.view.frame.size.width-200, 50)];
  168. // [self.photoBtn setTitle:@"相册" forState:UIControlStateNormal];
  169. // [self.photoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  170. // self.photoBtn.backgroundColor=[UIColor orangeColor];
  171. // [self.photoBtn addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  172. // [self.view addSubview:self.photoBtn];
  173. //9.开始扫描
  174. KWeakSelf
  175. globalBlock(^{
  176. [weakSelf.session startRunning];
  177. });
  178. //添加返回键
  179. CGFloat btn_w_h = 40;
  180. CGFloat btn_show = 28;
  181. UIButton *backBtn = [[UIButton alloc] init];
  182. [self.view addSubview:backBtn];
  183. [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
  184. make.top.mas_equalTo(H_STATE_BAR + (64.f - btn_w_h)/2.f);
  185. make.left.mas_equalTo(10);
  186. make.width.mas_equalTo(btn_w_h);
  187. make.height.mas_equalTo(btn_w_h);
  188. }];
  189. [backBtn setImage:[UIImage imageNamed:@"icon_base_back"] forState:(UIControlStateNormal)];
  190. [backBtn setImageEdgeInsets:(UIEdgeInsetsMake((btn_w_h - btn_show)/2.f, (btn_w_h - btn_show)/2.f, (btn_w_h - btn_show)/2.f, (btn_w_h - btn_show)/2.f))];
  191. [backBtn addTarget:self
  192. action:@selector(backBtnPressed)
  193. forControlEvents:(UIControlEventTouchUpInside)];
  194. }
  195. #pragma mark timer 处理线上下移动
  196. bool isScantoLoginDownType = YES;
  197. -(void)scanLineDownAndUpFun
  198. {
  199. [UIView animateWithDuration:0.01 animations:^{
  200. if(isScantoLoginDownType && self->_qrCodeScanLine.hw_y <= self->_cyanEdgeImageView.hw_h){
  201. self->_qrCodeScanLine.hw_y += 2;
  202. if(self->_cyanEdgeImageView.hw_h - self->_qrCodeScanLine.hw_y <= 5){
  203. isScantoLoginDownType = NO;
  204. }
  205. }
  206. else if(!isScantoLoginDownType && self->_qrCodeScanLine.hw_y >= 0)
  207. {
  208. self->_qrCodeScanLine.hw_y -= 2;
  209. if(self->_qrCodeScanLine.hw_y <= 5){
  210. isScantoLoginDownType = YES;
  211. }
  212. }
  213. }];
  214. }
  215. //实现扫描的回调代理方法
  216. - (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection{
  217. //如果数组metadataObjects中有数据,metadataObjects是个数组类型
  218. if(metadataObjects.count>0) {
  219. AVMetadataMachineReadableCodeObject*object = [metadataObjects lastObject];
  220. NSLog(@"%@",object.stringValue);
  221. /*扫描到有用信息时取消扫描*/
  222. NSString *resStr = object.stringValue;//RK3908P1V62112465
  223. [self handleScanCodeResultFun:resStr];
  224. }
  225. else{
  226. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  227. NSLog(@"没有扫描到数据");
  228. }
  229. }
  230. #pragma mark 处理扫码出来的数据
  231. - (void)handleScanCodeResultFun:(NSString*)resultStr
  232. {
  233. NSString * resStr = resultStr;
  234. if(resStr.length > 22)
  235. {
  236. NSString*desStr = [RSATool AES128Decrypt:resStr key:AESCODEKEEYY];
  237. if(desStr){//能解码
  238. resStr = desStr;
  239. }
  240. }
  241. //Ch0IKJCY9lOgokjfPBFE1cowdC1+tj7ywB2pZgSzjhc=
  242. //sgl5OzDoVjY5SmGuL50/EnQ4n6Kw+DzRiE1oUjq7yAM=
  243. if (([resStr containsString:@"RK"] && (resStr.length == @"RK3908P1V62112465".length))
  244. || resStr.length == @"0333933700223250017273".length
  245. ){
  246. [_scanLineTimer invalidate];
  247. //停止扫描
  248. [self.session stopRunning];
  249. //移除扫描层layer
  250. [self.layer removeFromSuperlayer];
  251. if(_didScanSNFun){
  252. _didScanSNFun(resStr);
  253. }
  254. //[self.navigationController popViewControllerAnimated:YES];
  255. [self.navigationController popToRootViewControllerAnimated:YES];
  256. }
  257. else{
  258. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  259. }
  260. }
  261. //光感传感器代理
  262. -(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection{
  263. //获取光线的值
  264. CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL,sampleBuffer, kCMAttachmentMode_ShouldPropagate);
  265. NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];
  266. CFRelease(metadataDict);
  267. NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
  268. float brightnessValue = [[exifMetadata objectForKey:(NSString*)kCGImagePropertyExifBrightnessValue]floatValue];
  269. NSLog(@"%f",brightnessValue);
  270. // 根据brightnessValue的值来打开和关闭闪光灯,一般值小于0就需要打开,大于0就关闭
  271. // if((brightnessValue <0)) {//显示闪光灯
  272. // self.lightBtn.hidden=NO;
  273. // }else if((brightnessValue >0)) {//隐藏闪光灯
  274. // self.lightBtn.hidden=YES;
  275. // }
  276. }
  277. ////闪光灯按钮点击方法
  278. //
  279. //-(void)lightBtnClick:(UIButton*)sender{
  280. // //判断当前设备是否有闪光灯
  281. //
  282. // AVCaptureDevice * device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  283. //
  284. // BOOL result=[device hasTorch];
  285. //
  286. // if(result==YES){
  287. // if(self.lightBtn.isSelected==NO){
  288. // self.lightBtn.selected=YES;
  289. // self.lightBtn.backgroundColor=[UIColor greenColor];
  290. // [device lockForConfiguration:nil];
  291. // [device setTorchMode: AVCaptureTorchModeOn];//开
  292. // [device unlockForConfiguration];
  293. // }else if(self.lightBtn.isSelected==YES){
  294. // self.lightBtn.selected=NO;
  295. // self.lightBtn.backgroundColor=[UIColor grayColor];
  296. // [device lockForConfiguration:nil];
  297. // [device setTorchMode: AVCaptureTorchModeOff];//关
  298. // [device unlockForConfiguration];
  299. // }
  300. // }else{
  301. // NSLog(@"当前设备闪光灯不可用");
  302. // }
  303. //}
  304. //
  305. ////获取相册图片btn点击方法
  306. -(void)photoBtnClick:(UIButton*)sender{
  307. // UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
  308. // imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  309. // // imagePicker.allowsEditing = YES;
  310. // imagePicker.delegate=self;
  311. // [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
  312. [self photoClickFun];
  313. }
  314. - (void)photoClickFun
  315. {
  316. TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
  317. imagePicker.allowPickingVideo=NO;
  318. //imagePicker.isStatusBarDefault=YES;
  319. imagePicker.allowTakePicture=NO;
  320. imagePicker.allowPreview = NO;
  321. // 4. 照片排列按修改时间升序
  322. imagePicker.sortAscendingByModificationDate = YES;
  323. [self presentViewController:imagePicker animated:YES completion:nil];
  324. }
  325. - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
  326. {
  327. if(photos && photos.count >= 1){
  328. [self detectImageFunBy:photos.firstObject];
  329. }
  330. else{
  331. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  332. }
  333. }
  334. //UIImagePickerControllerDelegate选择图片的回调
  335. -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
  336. //把UIimage类型转换成CIimage类型
  337. UIImage *pickedImage = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage];
  338. [picker dismissViewControllerAnimated:YES completion:^{
  339. }];
  340. [self detectImageFunBy:pickedImage];
  341. }
  342. #pragma mark 解析Uiimage
  343. - (void)detectImageFunBy:(UIImage*)pickedImage
  344. {
  345. CIImage*detectImage = [CIImage imageWithData:UIImagePNGRepresentation(pickedImage)];
  346. //解析扫描二维码结果字符串
  347. CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
  348. //CIQRCodeFeature*feature = (CIQRCodeFeature*)[detector featuresInImage:detectImage options:nil].firstObject;
  349. NSArray *messageStringArr = (CIQRCodeFeature*)[detector featuresInImage:detectImage options:nil];
  350. //排除掉 http的
  351. __block NSString *curQRCodeStr = nil;
  352. for(CIQRCodeFeature*feature in messageStringArr){
  353. if([feature.messageString rangeOfString:@"http"].location == NSNotFound){
  354. curQRCodeStr = feature.messageString;
  355. break;
  356. }
  357. }
  358. if(curQRCodeStr) {
  359. NSLog(@"=================二维码结果为%@",curQRCodeStr);
  360. [self handleScanCodeResultFun:curQRCodeStr];
  361. }else{
  362. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  363. NSLog(@"没有扫描到数据");
  364. }
  365. // //停止会话对象扫描
  366. // [self.session stopRunning];
  367. // //移除扫描层layer
  368. // [self.layer removeFromSuperlayer];
  369. }
  370. @end