scanToPCLoginViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. //
  2. // scanToPCLoginViewController.m
  3. // 双子星云手机
  4. //
  5. // Created by xd h on 2024/8/27.
  6. //
  7. #import "scanToPCLoginViewController.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. #import <ImageIO/ImageIO.h>
  10. #import "PCLoginViewController.h"
  11. @interface scanToPCLoginViewController ()<AVCaptureMetadataOutputObjectsDelegate,AVCaptureVideoDataOutputSampleBufferDelegate,UINavigationControllerDelegate>
  12. @property(nonatomic,strong)AVCaptureVideoPreviewLayer *layer;
  13. //捕捉会话
  14. @property(nonatomic,strong)AVCaptureSession *session;
  15. //辅助区域框
  16. @property(nonatomic,strong)UIImageView * cyanEdgeImageView;
  17. @property(nonatomic,strong)UIImageView * qrCodeScanLine;
  18. @property(nonatomic,strong)NSTimer * scanLineTimer;
  19. @end
  20. @implementation scanToPCLoginViewController
  21. - (void)viewDidLoad {
  22. [super viewDidLoad];
  23. // Do any additional setup after loading the view.
  24. [self.navigationBar setHidden:YES];
  25. [self.toolBar setHidden:YES];
  26. AVAuthorizationStatus authStatus =[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  27. //判断摄像头状态是否可用
  28. if(authStatus==AVAuthorizationStatusAuthorized){
  29. [self startScan];
  30. }else{
  31. NSLog(@"未开启相机权限,请前往设置中开启");
  32. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  33. if (granted){
  34. mainBlock(^{
  35. [self startScan];
  36. });
  37. }
  38. }];
  39. }
  40. }
  41. -(void)viewWillDisappear:(BOOL)animated
  42. {
  43. [super viewWillDisappear:animated];
  44. if(_scanLineTimer)[_scanLineTimer invalidate];
  45. }
  46. //开始扫描二维码
  47. -(void)startScan{
  48. //1.创建捕捉会话,AVCaptureSession是第一个要被创建的对象,所有的操作都要基于这一个session
  49. self.session = [[AVCaptureSession alloc]init];
  50. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  51. AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
  52. [self.session addInput:input];
  53. //3.添加输出数据(示例对象-->类对象-->元类对象-->根元类对象)
  54. /*输入的类是AVCaptureInput,那么输出的类相应的就应该是AVCaptureOutput。
  55.  输出不需要和设备挂钩,因为一般情况下,我们的输出要么是音频或视频文件,要么是一些其他的数据,像二维码扫描一般是字符串类型。
  56.  所以创建AVCaptureOutput实例就不需要AVCaptureDevice对象。
  57.  AVCaptureOutput也同样是一个抽象类,同样要使用其子类,在这里我们扫描二维码,
  58.  使用的是AVCaptureMetadataOutput,设置代码如下所示*/
  59. AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
  60. [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  61. //设置能扫描的区域,这里注意,CGRectMake的x,y和width,height的值是互换位置
  62. 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);
  63. [self.session addOutput:output];
  64. //设置输入元数据的类型(类型是二维码,条形码数据,注意,这个一定要写在添加到session后面,不然要崩溃,如果只需要扫描二维码只需要AVMetadataObjectTypeQRCode,如果还需要扫描条形码,那么全部添加上)
  65. [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,
  66. AVMetadataObjectTypeEAN8Code,
  67. AVMetadataObjectTypeEAN13Code,
  68. AVMetadataObjectTypeCode39Code,
  69. AVMetadataObjectTypeCode39Mod43Code,
  70. AVMetadataObjectTypeCode93Code,
  71. AVMetadataObjectTypeCode128Code,
  72. AVMetadataObjectTypePDF417Code,
  73. AVMetadataObjectTypeAztecCode,
  74. AVMetadataObjectTypeUPCECode,
  75. AVMetadataObjectTypeInterleaved2of5Code,
  76. AVMetadataObjectTypeITF14Code,
  77. AVMetadataObjectTypeDataMatrixCode,
  78. ]];
  79. //4.添加扫描图层
  80. self.layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
  81. self.layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
  82. self.layer.frame = self.view.bounds;
  83. [self.view.layer addSublayer:self.layer];
  84. //5.创建view,通过layer层进行设置边框宽度和颜色,用来辅助展示扫描的区域
  85. _cyanEdgeImageView=[[UIImageView alloc] initWithFrame:CGRectMake(100, 250, self.view.frame.size.width-200, self.view.frame.size.width-200)];
  86. // _cyanEdgeImageView.layer.borderWidth=2;
  87. //
  88. // _cyanEdgeImageView.layer.borderColor =[UIColor cyanColor].CGColor;
  89. _cyanEdgeImageView.image = [UIImage imageNamed:@"qrCode_scan_bg"];
  90. [self.view addSubview:_cyanEdgeImageView];
  91. _qrCodeScanLine=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-200, 1)];
  92. _qrCodeScanLine.image = [UIImage imageNamed:@"qrCode_scan_line"];
  93. [_cyanEdgeImageView addSubview:_qrCodeScanLine];
  94. _scanLineTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(scanLineDownAndUpFun) userInfo:nil repeats:YES];
  95. UILabel *tipLib = [[UILabel alloc] initWithFrame:CGRectMake(20, _cyanEdgeImageView.hw_max_y + 15, SCREEN_W - 40, 20)];
  96. tipLib.text = NSLocalizedString(@"pc_qrcoede_tips_please",nil);
  97. tipLib.font = [UIFont systemFontOfSize:14.0];
  98. tipLib.textAlignment = NSTextAlignmentCenter;
  99. tipLib.textColor = [UIColor whiteColor];
  100. [self.view addSubview:tipLib];
  101. //6.创建检测光感源
  102. AVCaptureVideoDataOutput *guangOutPut = [[AVCaptureVideoDataOutput alloc] init];
  103. [guangOutPut setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
  104. //设置为高质量采集率
  105. [self.session setSessionPreset:AVCaptureSessionPresetHigh];
  106. //把光感源添加到会话
  107. [self.session addOutput:guangOutPut];
  108. //9.开始扫描
  109. KWeakSelf
  110. globalBlock(^{
  111. [weakSelf.session startRunning];
  112. });
  113. //添加返回键
  114. CGFloat btn_w_h = 40;
  115. CGFloat btn_show = 28;
  116. UIButton *backBtn = [[UIButton alloc] init];
  117. [self.view addSubview:backBtn];
  118. [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
  119. make.top.mas_equalTo(H_STATE_BAR + (64.f - btn_w_h)/2.f);
  120. make.left.mas_equalTo(10);
  121. make.width.mas_equalTo(btn_w_h);
  122. make.height.mas_equalTo(btn_w_h);
  123. }];
  124. [backBtn setImage:[UIImage imageNamed:@"icon_white_back"] forState:(UIControlStateNormal)];
  125. [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))];
  126. [backBtn addTarget:self
  127. action:@selector(backBtnPressed)
  128. forControlEvents:(UIControlEventTouchUpInside)];
  129. //添加标题
  130. CGFloat left_ritght = btn_w_h + 10 + 5;
  131. UILabel *titleLabel = [[UILabel alloc] init];
  132. titleLabel.text = NSLocalizedString(@"pc_scan_to_login",nil);
  133. titleLabel.textAlignment = NSTextAlignmentCenter;
  134. titleLabel.font = [UIFont systemFontOfSize:16.0];
  135. titleLabel.textColor = [UIColor whiteColor];
  136. [self.view addSubview:titleLabel];
  137. [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  138. make.centerY.mas_equalTo(backBtn.mas_centerY);
  139. make.left.mas_equalTo(left_ritght);
  140. make.right.mas_equalTo(-left_ritght);
  141. make.height.mas_equalTo(btn_w_h);
  142. }];
  143. }
  144. #pragma mark timer 处理线上下移动
  145. bool isPCScanDownType = YES;
  146. -(void)scanLineDownAndUpFun
  147. {
  148. [UIView animateWithDuration:0.01 animations:^{
  149. if(isPCScanDownType && self->_qrCodeScanLine.hw_y <= self->_cyanEdgeImageView.hw_h){
  150. self->_qrCodeScanLine.hw_y += 2;
  151. if(self->_cyanEdgeImageView.hw_h - self->_qrCodeScanLine.hw_y <= 5){
  152. isPCScanDownType = NO;
  153. }
  154. }
  155. else if(!isPCScanDownType && self->_qrCodeScanLine.hw_y >= 0)
  156. {
  157. self->_qrCodeScanLine.hw_y -= 2;
  158. if(self->_qrCodeScanLine.hw_y <= 5){
  159. isPCScanDownType = YES;
  160. }
  161. }
  162. }];
  163. }
  164. //实现扫描的回调代理方法
  165. - (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputMetadataObjects:(NSArray*)metadataObjects fromConnection:(AVCaptureConnection*)connection{
  166. //如果数组metadataObjects中有数据,metadataObjects是个数组类型
  167. if(metadataObjects.count>0) {
  168. AVMetadataMachineReadableCodeObject*object = [metadataObjects lastObject];
  169. HLog(@"%@",object.stringValue);
  170. /*扫描到有用信息时取消扫描*/
  171. NSString *resStr = object.stringValue;//RK3908P1V62112465
  172. [self handleScanCodeResultFun:resStr];
  173. }
  174. else{
  175. [[iToast makeText:NSLocalizedString(@"pc_qrcoede_tips_error",nil)] show];
  176. HLog(@"没有扫描到数据");
  177. }
  178. }
  179. #pragma mark 处理扫码出来的数据
  180. - (void)handleScanCodeResultFun:(NSString*)resultStr
  181. {
  182. NSString * resStr = resultStr;
  183. if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)
  184. {
  185. [[iToast makeText:NSLocalizedString(@"phone_network_fail_Tips",nil)] show];
  186. return;
  187. }
  188. if ([resStr containsString:@"boxLoginId:"]){
  189. [_scanLineTimer invalidate];
  190. [self scanToPCloginFunWithID:resStr];
  191. //停止扫描
  192. [self.session stopRunning];
  193. //移除扫描层layer
  194. [self.layer removeFromSuperlayer];
  195. }
  196. else{
  197. [[iToast makeText:NSLocalizedString(@"pc_qrcoede_tips_error",nil)] show];
  198. }
  199. }
  200. //光感传感器代理
  201. -(void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection{
  202. //获取光线的值
  203. CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL,sampleBuffer, kCMAttachmentMode_ShouldPropagate);
  204. NSDictionary *metadata = [[NSMutableDictionary alloc] initWithDictionary:(__bridge NSDictionary*)metadataDict];
  205. CFRelease(metadataDict);
  206. NSDictionary *exifMetadata = [[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
  207. float brightnessValue = [[exifMetadata objectForKey:(NSString*)kCGImagePropertyExifBrightnessValue]floatValue];
  208. NSLog(@"%f",brightnessValue);
  209. // 根据brightnessValue的值来打开和关闭闪光灯,一般值小于0就需要打开,大于0就关闭
  210. // if((brightnessValue <0)) {//显示闪光灯
  211. // self.lightBtn.hidden=NO;
  212. // }else if((brightnessValue >0)) {//隐藏闪光灯
  213. // self.lightBtn.hidden=YES;
  214. // }
  215. }
  216. ////闪光灯按钮点击方法
  217. //
  218. //-(void)lightBtnClick:(UIButton*)sender{
  219. // //判断当前设备是否有闪光灯
  220. //
  221. // AVCaptureDevice * device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  222. //
  223. // BOOL result=[device hasTorch];
  224. //
  225. // if(result==YES){
  226. // if(self.lightBtn.isSelected==NO){
  227. // self.lightBtn.selected=YES;
  228. // self.lightBtn.backgroundColor=[UIColor greenColor];
  229. // [device lockForConfiguration:nil];
  230. // [device setTorchMode: AVCaptureTorchModeOn];//开
  231. // [device unlockForConfiguration];
  232. // }else if(self.lightBtn.isSelected==YES){
  233. // self.lightBtn.selected=NO;
  234. // self.lightBtn.backgroundColor=[UIColor grayColor];
  235. // [device lockForConfiguration:nil];
  236. // [device setTorchMode: AVCaptureTorchModeOff];//关
  237. // [device unlockForConfiguration];
  238. // }
  239. // }else{
  240. // NSLog(@"当前设备闪光灯不可用");
  241. // }
  242. //}
  243. #pragma mark PC 扫码登录
  244. -(void)scanToPCloginFunWithID:(NSString*)idStr
  245. {
  246. NSString *changSN = ksharedAppDelegate.DeviceThirdIdMod.data.changeSn;
  247. NSMutableDictionary *paraDict = [NSMutableDictionary new];
  248. [paraDict setValue:@1 forKey:@"status"];
  249. [paraDict setValue:idStr forKey:@"boxLoginId"];
  250. [paraDict setValue:changSN forKey:@"sn"];
  251. KWeakSelf
  252. [[netWorkManager shareInstance] CommonPostCallBackCode:updatePCLoginStateFun Parameters:paraDict success:^(id _Nonnull responseObject){
  253. SuperModel *curModel = [[SuperModel alloc] initWithDictionary:responseObject error:nil];
  254. if(curModel && curModel.status == 0){
  255. [weakSelf gotoNextVCFunWithID:idStr];
  256. }
  257. else
  258. {
  259. if(curModel.msg){
  260. [[iToast makeText:curModel.msg] show];
  261. }
  262. else{
  263. [[iToast makeText:NSLocalizedString(@"pc_qrcoede_tips_error",nil)] show];
  264. }
  265. [weakSelf.navigationController popViewControllerAnimated:YES];
  266. }
  267. } failure:^(NSError * _Nonnull error) {
  268. //[[iToast makeText:@"扫码信息错误"] show];
  269. [weakSelf.navigationController popViewControllerAnimated:YES];
  270. }];
  271. }
  272. #pragma mark 跳转下个界面
  273. - (void)gotoNextVCFunWithID:(NSString*)idStr
  274. {
  275. // NSArray *vcArr = self.navigationController.viewControllers;
  276. //
  277. // NSMutableArray * newArr = [NSMutableArray new];
  278. //
  279. // for (int i=0; i< vcArr.count-1; i++) {
  280. // UIViewController *vc = vcArr[i];
  281. // [newArr addObject:vc];
  282. // }
  283. //
  284. // self.navigationController.viewControllers = newArr;
  285. //
  286. // vcArr = self.navigationController.viewControllers;
  287. PCLoginViewController *nextVC = [PCLoginViewController new];
  288. nextVC.loginIdString = idStr;
  289. [self.navigationController pushViewController:nextVC animated:YES];
  290. }
  291. @end