QRCodeViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. //
  2. // QRCodeViewController.m
  3. // kneet
  4. //
  5. // Created by Jason Lee on 5/18/15.
  6. // Copyright (c) 2015 ntels. All rights reserved.
  7. //
  8. @import AVFoundation;
  9. #import "QRCodeViewController.h"
  10. #import "JDObject.h"
  11. #import "QRCodeInputPopupView.h"
  12. #import "CustomTextField.h"
  13. #import "UIDeviceUtil.h"
  14. #import "SecureThingsViewController.h"
  15. #import "RequestHandler.h"
  16. #import "SecureChangeViewController.h"
  17. @interface QRCodeViewController () <AVCaptureMetadataOutputObjectsDelegate> {
  18. CGRect _captureRect;
  19. QRCodeInputPopupView *_inputPopup;
  20. AVAuthorizationStatus _avAuthrizationStatus;
  21. }
  22. @property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
  23. @property (nonatomic, strong) CALayer *targetLayer;
  24. @property (nonatomic, strong) CAShapeLayer *guideLayer;
  25. @property (nonatomic, strong) AVCaptureSession *captureSession;
  26. @property (nonatomic, strong) NSMutableArray *codeObjects;
  27. @end
  28. #pragma mark - Class Definition
  29. @implementation QRCodeViewController
  30. - (void)viewDidLoad {
  31. [super viewDidLoad];
  32. // Do any additional setup after loading the view.
  33. [self initUI];
  34. [self prepareViewDidLoad];
  35. }
  36. - (void)initUI {
  37. }
  38. - (void)prepareViewDidLoad {
  39. }
  40. - (void)viewDidAppear:(BOOL)animated
  41. {
  42. [super viewDidAppear:animated];
  43. [[NSNotificationCenter defaultCenter] addObserver:self
  44. selector:@selector(applicationDidEnterBackground:)
  45. name:UIApplicationDidEnterBackgroundNotification
  46. object:nil];
  47. [[NSNotificationCenter defaultCenter] addObserver:self
  48. selector:@selector(applicationWillEnterForeground:)
  49. name:UIApplicationWillEnterForegroundNotification
  50. object:nil];
  51. [self startRunning];
  52. }
  53. - (void)viewWillDisappear:(BOOL)animated
  54. {
  55. [super viewWillDisappear:animated];
  56. [[NSNotificationCenter defaultCenter] removeObserver:self];
  57. [self stopRunning];
  58. }
  59. - (void)applicationDidEnterBackground:(NSNotification *)notification
  60. {
  61. [self stopRunning];
  62. }
  63. - (void)applicationWillEnterForeground:(NSNotification *)notification
  64. {
  65. [self startRunning];
  66. }
  67. #pragma mark - Main Logic
  68. - (NSMutableArray *)codeObjects
  69. {
  70. if (!_codeObjects)
  71. {
  72. _codeObjects = [NSMutableArray new];
  73. }
  74. return _codeObjects;
  75. }
  76. - (void)requestQRAuthrize:(NSString *)activationCode password:(NSString *)password {
  77. //parameters
  78. NSDictionary *parameter = @{@"activation_code": activationCode,
  79. @"user_device_password": password};
  80. NSString *path = [NSString stringWithFormat:API_POST_PARTNER_QR];
  81. [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[QRAuthModel class] completion:^(id responseObject) {
  82. if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
  83. return;
  84. }
  85. QRAuthModel *qauth = (QRAuthModel *) responseObject;
  86. if (qauth) {//API 성공 ,
  87. UIViewController *vc = nil;
  88. if ([qauth.passwordYn boolValue]) {//사용자 설정 상태 - 비밀번호 변경,
  89. SecureChangeViewController *cvc = (SecureChangeViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"SecureChangeViewController" storyboardName:@"Things"];
  90. cvc.deviceId = qauth.deviceId;
  91. cvc.qrcodeType = _qrcodeType;
  92. vc = cvc;
  93. } else {//초기화
  94. SecureThingsViewController *tvc = (SecureThingsViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"SecureThingsViewController" storyboardName:@"Things"];
  95. tvc.deviceId = qauth.deviceId;
  96. tvc.qrcodeType = _qrcodeType;
  97. vc = tvc;
  98. }
  99. UINavigationController *nc = [[UINavigationController alloc] init];
  100. nc.viewControllers = @[vc];
  101. [[JDFacade facade] presentViewControllerByPush:nc pvc:self];
  102. }
  103. } failure:^(id errorObject) {
  104. JDErrorModel *error = (JDErrorModel *)errorObject;
  105. [[JDFacade facade] alert:error.errorMessage];
  106. #ifdef DEBUG_MODE
  107. [[JDFacade facade] dismissViewControllerByPush:self];
  108. #endif
  109. }];
  110. }
  111. #pragma mark - Main Logic
  112. - (AVCaptureSession *)captureSession
  113. {
  114. if (!_captureSession)
  115. {
  116. NSError *error = nil;
  117. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  118. if (device.isAutoFocusRangeRestrictionSupported)
  119. {
  120. if ([device lockForConfiguration:&error])
  121. {
  122. [device setAutoFocusRangeRestriction:AVCaptureAutoFocusRangeRestrictionNear];
  123. [device unlockForConfiguration];
  124. }
  125. }
  126. // The first time AVCaptureDeviceInput creation will present a dialog to the user
  127. // requesting camera access. If the user refuses the creation fails.
  128. // See WWDC 2013 session #610 for details, but note this behaviour does not seem to
  129. // be enforced on iOS 7 where as it is with iOS 8.
  130. AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
  131. if (deviceInput)
  132. {
  133. _captureSession = [[AVCaptureSession alloc] init];
  134. if ([_captureSession canAddInput:deviceInput])
  135. {
  136. [_captureSession addInput:deviceInput];
  137. }
  138. AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
  139. if ([_captureSession canAddOutput:metadataOutput])
  140. {
  141. [_captureSession addOutput:metadataOutput];
  142. [metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  143. [metadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
  144. }
  145. //카메라 프리뷰 레이어
  146. self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
  147. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  148. self.previewLayer.frame = self.view.bounds;
  149. [self.view.layer addSublayer:self.previewLayer];
  150. //가이드 레이어 작성
  151. UIImage *imgGuide = [UIImage imageNamed:@"tp_01_img_thingsadd_reg_02_QR_areapoint"];
  152. CGFloat orix = (IPHONE_WIDTH - imgGuide.size.width) / 2;
  153. CGFloat oriy = (IPHONE_HEIGHT - _conainerView.frame.size.height - imgGuide.size.height) / 2;
  154. _captureRect = CGRectMake(orix, oriy, imgGuide.size.width, imgGuide.size.height);
  155. self.guideLayer = [CAShapeLayer layer];
  156. self.guideLayer.contents = (id)[imgGuide CGImage];
  157. self.guideLayer.frame = _captureRect;
  158. // self.guideLayer.fillColor = nil;
  159. // self.guideLayer.strokeColor = [UIColor grayColor].CGColor;
  160. // self.guideLayer.lineWidth = 10.0f;
  161. [self.view.layer addSublayer:self.guideLayer];
  162. [self.view addSubview:_conainerView];
  163. CGFloat width = [CommonUtil hardware] == IPHONE_6 ? 375 : 320;
  164. width = [CommonUtil hardware] == IPHONE_6_PLUS ? 414 : width;
  165. [_conainerView mas_makeConstraints:^(MASConstraintMaker *make) {
  166. make.size.width.mas_equalTo(self.view.frame.size.width);
  167. make.bottom.equalTo(self.view.mas_baseline);
  168. }];
  169. }
  170. else
  171. {
  172. NSLog(@"Input Device error: %@",[error localizedDescription]);
  173. [self showAlertForCameraError:error];
  174. }
  175. }
  176. return _captureSession;
  177. }
  178. #pragma mark - AVCaptureMetadataOutputObjectsDelegate
  179. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
  180. {
  181. self.codeObjects = nil;
  182. for (AVMetadataObject *metadataObject in metadataObjects)
  183. {
  184. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:metadataObject];
  185. if ([transformed.type isEqualToString:AVMetadataObjectTypeQRCode]) {
  186. // Update the frame on the _boundingBox view, and show it
  187. CGRect mr = transformed.bounds;
  188. if (CGRectContainsRect(_captureRect, mr)) {
  189. NSLog(@"%@", transformed.stringValue);
  190. [self stopRunning];
  191. [self gotoSetSecurityOfDevice:transformed.stringValue];
  192. }
  193. }
  194. }
  195. }
  196. - (void)showAlertForCameraError:(NSError *)error
  197. {
  198. NSString *message = error.localizedFailureReason ? error.localizedFailureReason : error.localizedDescription;
  199. [[JDFacade facade] alert:message];
  200. }
  201. - (void)startRunning
  202. {
  203. #if TARGET_IPHONE_SIMULATOR
  204. [self btnInsertTouched:nil];
  205. return;
  206. #endif
  207. _avAuthrizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  208. if (_avAuthrizationStatus != AVAuthorizationStatusAuthorized) {//카메라 권한이 없을 경우,
  209. NSString *message = MSG_CAMERA_DISABLE;
  210. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") delegate:nil OKButtonTitle:NSLocalizedString(@"설정", @"설정") cancelButtonTitle:NSLocalizedString(@"취소", @"취소") message:message, nil];
  211. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  212. if (buttonIndex == 0) {//OK - 이전화면으로
  213. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  214. [[UIApplication sharedApplication] openURL:settingsURL];
  215. return;
  216. } else {
  217. [self btnInsertTouched:nil]; //직접 입력창을 띄움.
  218. }
  219. }];
  220. } else {//권한이 있을 경우,
  221. self.codeObjects = nil;
  222. [self.captureSession startRunning];
  223. // [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  224. // if (granted) {
  225. // }
  226. // }];
  227. }
  228. }
  229. - (void)stopRunning
  230. {
  231. #if TARGET_IPHONE_SIMULATOR
  232. return;
  233. #endif
  234. [self.captureSession stopRunning];
  235. self.captureSession = nil;
  236. }
  237. - (void)clearTargetLayer
  238. {
  239. // NSArray *sublayers = [[self.targetLayer sublayers] copy];
  240. // for (CALayer *sublayer in sublayers)
  241. // {
  242. // [sublayer removeFromSuperlayer];
  243. // }
  244. }
  245. - (void)showDetectedObjects
  246. {
  247. for (AVMetadataObject *metadata in self.codeObjects)
  248. {
  249. if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {
  250. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:metadata];
  251. // Update the frame on the _boundingBox view, and show it
  252. CGRect mr = transformed.bounds;
  253. if (CGRectContainsRect(self.guideLayer.frame, mr)) {
  254. CAShapeLayer *shapeLayer = [CAShapeLayer layer];
  255. // shapeLayer.strokeColor = [UIColor redColor].CGColor;
  256. // shapeLayer.fillColor = [UIColor clearColor].CGColor;
  257. // shapeLayer.lineWidth = 2.0;
  258. // shapeLayer.lineJoin = kCALineJoinRound;
  259. CGPathRef path = createPathForPoints([(AVMetadataMachineReadableCodeObject *)metadata corners]);
  260. shapeLayer.path = path;
  261. CGRect *pr = nil;
  262. if (CGPathIsRect(path, pr)) {
  263. NSLog(@"%@", NSStringFromCGRect(*pr));
  264. // if (CGPathEqualToPath(self.guideLayer.path, path)) {
  265. NSLog(@"same");
  266. } else {
  267. NSLog(@"not");
  268. }
  269. // CFRelease(path);
  270. // [self.targetLayer addSublayer:shapeLayer];
  271. } else {
  272. }
  273. }
  274. }
  275. }
  276. CGMutablePathRef createPathForPoints(NSArray* points)
  277. {
  278. CGMutablePathRef path = CGPathCreateMutable();
  279. CGPoint point;
  280. if ([points count] > 0)
  281. {
  282. CGPointMakeWithDictionaryRepresentation((CFDictionaryRef)[points objectAtIndex:0], &point);
  283. CGPathMoveToPoint(path, nil, point.x, point.y);
  284. int i = 1;
  285. while (i < [points count])
  286. {
  287. CGPointMakeWithDictionaryRepresentation((CFDictionaryRef)[points objectAtIndex:i], &point);
  288. CGPathAddLineToPoint(path, nil, point.x, point.y);
  289. i++;
  290. }
  291. CGPathCloseSubpath(path);
  292. }
  293. return path;
  294. }
  295. - (void)gotoSetSecurityOfDevice:(NSString *)QRCode {
  296. NSArray *qrs = [QRCode componentsSeparatedByString:@"|"];
  297. if (!qrs || qrs.count < 3 || ![qrs[1] isEqualToString:@"*_AC_*"]) {//니트 디바이스
  298. [[JDFacade facade] alert:NSLocalizedString(@"서비스 지원장치가 아닙니다", @"서비스 지원장치가 아닙니다")];
  299. return;
  300. }
  301. [self requestQRAuthrize:qrs[0] password:qrs[2]];
  302. }
  303. #pragma mark - UI Events
  304. - (void)btnInsertTouched:(id)sender {
  305. if (!_inputPopup) {
  306. _inputPopup = [[QRCodeInputPopupView alloc] initFromNib];
  307. }
  308. _inputPopup.qrcodeType = _qrcodeType;
  309. _inputPopup.txtActivationCode.text = ksEmptyString;
  310. [_inputPopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  311. if (buttonIndex == 0) {//OK
  312. [self requestQRAuthrize:_inputPopup.txtActivationCode.text password:_inputPopup.txtPasswd.text];
  313. } else {
  314. if (_avAuthrizationStatus != AVAuthorizationStatusAuthorized) {//카메라 권한이 없을 경우, 리턴,
  315. [self btnCancelTouched:nil];
  316. }
  317. }
  318. }];
  319. }
  320. - (void)btnCancelTouched:(id)sender {
  321. [[JDFacade facade] dismissViewControllerByPush:self];
  322. }
  323. #pragma mark - MemoryWarning
  324. - (void)didReceiveMemoryWarning
  325. {
  326. [super didReceiveMemoryWarning];
  327. // Dispose of any resources that can be recreated.
  328. }
  329. @end