ScanToLoginViewController.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. [self.session startRunning];
  175. //添加返回键
  176. CGFloat btn_w_h = 40;
  177. CGFloat btn_show = 28;
  178. UIButton *backBtn = [[UIButton alloc] init];
  179. [self.view addSubview:backBtn];
  180. [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
  181. make.top.mas_equalTo(H_STATE_BAR + (64.f - btn_w_h)/2.f);
  182. make.left.mas_equalTo(10);
  183. make.width.mas_equalTo(btn_w_h);
  184. make.height.mas_equalTo(btn_w_h);
  185. }];
  186. [backBtn setImage:[UIImage imageNamed:@"icon_base_back"] forState:(UIControlStateNormal)];
  187. [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))];
  188. [backBtn addTarget:self
  189. action:@selector(backBtnPressed)
  190. forControlEvents:(UIControlEventTouchUpInside)];
  191. }
  192. #pragma mark timer 处理线上下移动
  193. bool isScantoLoginDownType = YES;
  194. -(void)scanLineDownAndUpFun
  195. {
  196. [UIView animateWithDuration:0.01 animations:^{
  197. if(isScantoLoginDownType && self->_qrCodeScanLine.hw_y <= self->_cyanEdgeImageView.hw_h){
  198. self->_qrCodeScanLine.hw_y += 2;
  199. if(self->_cyanEdgeImageView.hw_h - self->_qrCodeScanLine.hw_y <= 5){
  200. isScantoLoginDownType = NO;
  201. }
  202. }
  203. else if(!isScantoLoginDownType && self->_qrCodeScanLine.hw_y >= 0)
  204. {
  205. self->_qrCodeScanLine.hw_y -= 2;
  206. if(self->_qrCodeScanLine.hw_y <= 5){
  207. isScantoLoginDownType = YES;
  208. }
  209. }
  210. }];
  211. }
  212. //实现扫描的回调代理方法
  213. - (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection{
  214. //如果数组metadataObjects中有数据,metadataObjects是个数组类型
  215. if(metadataObjects.count>0) {
  216. AVMetadataMachineReadableCodeObject*object = [metadataObjects lastObject];
  217. NSLog(@"%@",object.stringValue);
  218. /*扫描到有用信息时取消扫描*/
  219. NSString *resStr = object.stringValue;//RK3908P1V62112465
  220. [self handleScanCodeResultFun:resStr];
  221. }
  222. else{
  223. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  224. NSLog(@"没有扫描到数据");
  225. }
  226. }
  227. #pragma mark 处理扫码出来的数据
  228. - (void)handleScanCodeResultFun:(NSString*)resultStr
  229. {
  230. NSString * resStr = resultStr;
  231. if(resStr.length > 22)
  232. {
  233. NSString*desStr = [RSATool AES128Decrypt:resStr key:AESCODEKEEYY];
  234. if(desStr){//能解码
  235. resStr = desStr;
  236. }
  237. }
  238. //Ch0IKJCY9lOgokjfPBFE1cowdC1+tj7ywB2pZgSzjhc=
  239. //sgl5OzDoVjY5SmGuL50/EnQ4n6Kw+DzRiE1oUjq7yAM=
  240. if (([resStr containsString:@"RK"] && (resStr.length == @"RK3908P1V62112465".length))
  241. || resStr.length == @"0333933700223250017273".length
  242. ){
  243. [_scanLineTimer invalidate];
  244. //停止扫描
  245. [self.session stopRunning];
  246. //移除扫描层layer
  247. [self.layer removeFromSuperlayer];
  248. if(_didScanSNFun){
  249. _didScanSNFun(resStr);
  250. }
  251. [self.navigationController popViewControllerAnimated:YES];
  252. }
  253. else{
  254. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  255. }
  256. }
  257. //光感传感器代理
  258. -(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection{
  259. //获取光线的值
  260. CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL,sampleBuffer, kCMAttachmentMode_ShouldPropagate);
  261. NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];
  262. CFRelease(metadataDict);
  263. NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
  264. float brightnessValue = [[exifMetadata objectForKey:(NSString*)kCGImagePropertyExifBrightnessValue]floatValue];
  265. NSLog(@"%f",brightnessValue);
  266. // 根据brightnessValue的值来打开和关闭闪光灯,一般值小于0就需要打开,大于0就关闭
  267. // if((brightnessValue <0)) {//显示闪光灯
  268. // self.lightBtn.hidden=NO;
  269. // }else if((brightnessValue >0)) {//隐藏闪光灯
  270. // self.lightBtn.hidden=YES;
  271. // }
  272. }
  273. ////闪光灯按钮点击方法
  274. //
  275. //-(void)lightBtnClick:(UIButton*)sender{
  276. // //判断当前设备是否有闪光灯
  277. //
  278. // AVCaptureDevice * device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  279. //
  280. // BOOL result=[device hasTorch];
  281. //
  282. // if(result==YES){
  283. // if(self.lightBtn.isSelected==NO){
  284. // self.lightBtn.selected=YES;
  285. // self.lightBtn.backgroundColor=[UIColor greenColor];
  286. // [device lockForConfiguration:nil];
  287. // [device setTorchMode: AVCaptureTorchModeOn];//开
  288. // [device unlockForConfiguration];
  289. // }else if(self.lightBtn.isSelected==YES){
  290. // self.lightBtn.selected=NO;
  291. // self.lightBtn.backgroundColor=[UIColor grayColor];
  292. // [device lockForConfiguration:nil];
  293. // [device setTorchMode: AVCaptureTorchModeOff];//关
  294. // [device unlockForConfiguration];
  295. // }
  296. // }else{
  297. // NSLog(@"当前设备闪光灯不可用");
  298. // }
  299. //}
  300. //
  301. ////获取相册图片btn点击方法
  302. -(void)photoBtnClick:(UIButton*)sender{
  303. // UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
  304. // imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  305. // // imagePicker.allowsEditing = YES;
  306. // imagePicker.delegate=self;
  307. // [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
  308. [self photoClickFun];
  309. }
  310. - (void)photoClickFun
  311. {
  312. TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
  313. imagePicker.allowPickingVideo=NO;
  314. //imagePicker.isStatusBarDefault=YES;
  315. imagePicker.allowTakePicture=NO;
  316. imagePicker.allowPreview = NO;
  317. // 4. 照片排列按修改时间升序
  318. imagePicker.sortAscendingByModificationDate = YES;
  319. [self presentViewController:imagePicker animated:YES completion:nil];
  320. }
  321. - (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
  322. {
  323. if(photos && photos.count >= 1){
  324. [self detectImageFunBy:photos.firstObject];
  325. }
  326. else{
  327. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  328. }
  329. }
  330. //UIImagePickerControllerDelegate选择图片的回调
  331. -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
  332. //把UIimage类型转换成CIimage类型
  333. UIImage *pickedImage = info[UIImagePickerControllerEditedImage] ?: info[UIImagePickerControllerOriginalImage];
  334. [picker dismissViewControllerAnimated:YES completion:^{
  335. }];
  336. [self detectImageFunBy:pickedImage];
  337. }
  338. #pragma mark 解析Uiimage
  339. - (void)detectImageFunBy:(UIImage*)pickedImage
  340. {
  341. CIImage*detectImage = [CIImage imageWithData:UIImagePNGRepresentation(pickedImage)];
  342. //解析扫描二维码结果字符串
  343. CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
  344. //CIQRCodeFeature*feature = (CIQRCodeFeature*)[detector featuresInImage:detectImage options:nil].firstObject;
  345. NSArray *messageStringArr = (CIQRCodeFeature*)[detector featuresInImage:detectImage options:nil];
  346. //排除掉 http的
  347. __block NSString *curQRCodeStr = nil;
  348. for(CIQRCodeFeature*feature in messageStringArr){
  349. if([feature.messageString rangeOfString:@"http"].location == NSNotFound){
  350. curQRCodeStr = feature.messageString;
  351. break;
  352. }
  353. }
  354. if(curQRCodeStr) {
  355. NSLog(@"=================二维码结果为%@",curQRCodeStr);
  356. [self handleScanCodeResultFun:curQRCodeStr];
  357. }else{
  358. [[iToast makeText:NSLocalizedString(@"guide_qrcoede_tips_error",nil)] show];
  359. NSLog(@"没有扫描到数据");
  360. }
  361. // //停止会话对象扫描
  362. // [self.session stopRunning];
  363. // //移除扫描层layer
  364. // [self.layer removeFromSuperlayer];
  365. }
  366. @end