QRCodeViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 "JDObject.h"
  10. #import "RequestHandler.h"
  11. #import "CustomTextField.h"
  12. #import "QRCodeInputPopupView.h"
  13. #import "UIDeviceUtil.h"
  14. #import "QRCodeViewController.h"
  15. #import "HomeHubInitViewController.h"
  16. #import "HomeHubChangeViewController.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. @"activation_password": password};
  80. NSString *path = [NSString stringWithFormat:API_GET_PARTNER_QR];
  81. [[RequestHandler handler] sendAsyncGetRequestAPIPath: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.ownerYn boolValue]) {//N : 장치의 소유자가 없음.(새 비밀번호 지정 필요)
  89. HomeHubInitViewController *tvc = (HomeHubInitViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubInitViewController" storyboardName:@"HomeHub"];
  90. tvc.activationCode = activationCode;
  91. tvc.activationPassword = password;
  92. vc = tvc;
  93. } else {//Y : 장치의 소유자가 있음.(이전 비밀번호 확인 필요)
  94. HomeHubChangeViewController *cvc = (HomeHubChangeViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"HomeHubChangeViewController" storyboardName:@"HomeHub"];
  95. cvc.activationCode = activationCode;
  96. cvc.activationPassword = password;
  97. vc = cvc;
  98. }
  99. if (_inputPopup && _inputPopup.superview) {
  100. [_inputPopup hide];
  101. }
  102. [self presentViewController:vc animated:YES completion:nil];
  103. }
  104. } failure:^(id errorObject) {
  105. JDErrorModel *error = (JDErrorModel *)errorObject;
  106. [[JDFacade facade] toast:error.errorMessage];
  107. }];
  108. }
  109. #pragma mark - Main Logic
  110. - (AVCaptureSession *)captureSession
  111. {
  112. if (!_captureSession)
  113. {
  114. NSError *error = nil;
  115. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  116. if (device.isAutoFocusRangeRestrictionSupported)
  117. {
  118. if ([device lockForConfiguration:&error])
  119. {
  120. [device setAutoFocusRangeRestriction:AVCaptureAutoFocusRangeRestrictionNear];
  121. [device unlockForConfiguration];
  122. }
  123. }
  124. // The first time AVCaptureDeviceInput creation will present a dialog to the user
  125. // requesting camera access. If the user refuses the creation fails.
  126. // See WWDC 2013 session #610 for details, but note this behaviour does not seem to
  127. // be enforced on iOS 7 where as it is with iOS 8.
  128. AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
  129. if (deviceInput)
  130. {
  131. _captureSession = [[AVCaptureSession alloc] init];
  132. if ([_captureSession canAddInput:deviceInput])
  133. {
  134. [_captureSession addInput:deviceInput];
  135. }
  136. AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc] init];
  137. if ([_captureSession canAddOutput:metadataOutput])
  138. {
  139. [_captureSession addOutput:metadataOutput];
  140. [metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  141. [metadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
  142. }
  143. //카메라 프리뷰 레이어
  144. self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
  145. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  146. self.previewLayer.frame = self.view.bounds;
  147. [self.view.layer addSublayer:self.previewLayer];
  148. //가이드 레이어 작성
  149. UIImage *imgGuide = [UIImage imageNamed:@"tp_01_img_thingsadd_reg_02_QR_areapoint"];
  150. CGFloat orix = (IPHONE_WIDTH - imgGuide.size.width) / 2;
  151. CGFloat oriy = (IPHONE_HEIGHT - _containerView.frame.size.height - imgGuide.size.height) / 2;
  152. _captureRect = CGRectMake(orix, oriy, imgGuide.size.width, imgGuide.size.height);
  153. self.guideLayer = [CAShapeLayer layer];
  154. self.guideLayer.contents = (id)[imgGuide CGImage];
  155. self.guideLayer.frame = _captureRect;
  156. // self.guideLayer.fillColor = nil;
  157. // self.guideLayer.strokeColor = [UIColor grayColor].CGColor;
  158. // self.guideLayer.lineWidth = 10.0f;
  159. [self.view.layer addSublayer:self.guideLayer];
  160. [self.view addSubview:_containerView];
  161. CGFloat width = [CommonUtil hardware] == IPHONE_6 ? 375 : 320;
  162. width = [CommonUtil hardware] == IPHONE_6_PLUS ? 414 : width;
  163. [_containerView mas_makeConstraints:^(MASConstraintMaker *make) {
  164. make.size.width.mas_equalTo(self.view.frame.size.width);
  165. make.bottom.equalTo(self.view.mas_baseline);
  166. }];
  167. }
  168. else
  169. {
  170. NSLog(@"Input Device error: %@",[error localizedDescription]);
  171. [self showAlertForCameraError:error];
  172. }
  173. }
  174. return _captureSession;
  175. }
  176. #pragma mark - AVCaptureMetadataOutputObjectsDelegate
  177. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
  178. {
  179. self.codeObjects = nil;
  180. for (AVMetadataObject *metadataObject in metadataObjects)
  181. {
  182. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:metadataObject];
  183. if ([transformed.type isEqualToString:AVMetadataObjectTypeQRCode]) {
  184. // Update the frame on the _boundingBox view, and show it
  185. CGRect mr = transformed.bounds;
  186. if (CGRectContainsRect(_captureRect, mr)) {
  187. NSLog(@"%@", transformed.stringValue);
  188. [self stopRunning];
  189. [self gotoSetSecurityOfDevice:transformed.stringValue];
  190. }
  191. }
  192. }
  193. }
  194. - (void)showAlertForCameraError:(NSError *)error
  195. {
  196. NSString *message = error.localizedFailureReason ? error.localizedFailureReason : error.localizedDescription;
  197. [[JDFacade facade] alert:message];
  198. }
  199. - (void)startRunning
  200. {
  201. #if TARGET_IPHONE_SIMULATOR
  202. [self btnInsertTouched:nil];
  203. return;
  204. #endif
  205. _avAuthrizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  206. if (_avAuthrizationStatus != AVAuthorizationStatusAuthorized) {//카메라 권한이 없을 경우,
  207. NSString *message = MSG_CAMERA_DISABLE;
  208. CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:@"알림" message:message delegate:nil OKButtonTitle:@"설정" cancelButtonTitle:@"취소"];
  209. [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  210. if (buttonIndex == 0) {//OK - 이전화면으로
  211. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  212. [[UIApplication sharedApplication] openURL:settingsURL];
  213. return;
  214. } else {
  215. [self btnInsertTouched:nil]; //직접 입력창을 띄움.
  216. }
  217. }];
  218. } else {//권한이 있을 경우,
  219. self.codeObjects = nil;
  220. [self.captureSession startRunning];
  221. // [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  222. // if (granted) {
  223. // }
  224. // }];
  225. }
  226. }
  227. - (void)stopRunning
  228. {
  229. #if TARGET_IPHONE_SIMULATOR
  230. return;
  231. #endif
  232. [self.captureSession stopRunning];
  233. self.captureSession = nil;
  234. }
  235. - (void)clearTargetLayer
  236. {
  237. // NSArray *sublayers = [[self.targetLayer sublayers] copy];
  238. // for (CALayer *sublayer in sublayers)
  239. // {
  240. // [sublayer removeFromSuperlayer];
  241. // }
  242. }
  243. - (void)showDetectedObjects
  244. {
  245. for (AVMetadataObject *metadata in self.codeObjects) {
  246. if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {
  247. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:metadata];
  248. // Update the frame on the _boundingBox view, and show it
  249. CGRect mr = transformed.bounds;
  250. if (CGRectContainsRect(self.guideLayer.frame, mr)) {
  251. CAShapeLayer *shapeLayer = [CAShapeLayer layer];
  252. // shapeLayer.strokeColor = [UIColor redColor].CGColor;
  253. // shapeLayer.fillColor = [UIColor clearColor].CGColor;
  254. // shapeLayer.lineWidth = 2.0;
  255. // shapeLayer.lineJoin = kCALineJoinRound;
  256. CGPathRef path = createPathForPoints([(AVMetadataMachineReadableCodeObject *)metadata corners]);
  257. shapeLayer.path = path;
  258. CGRect *pr = nil;
  259. if (CGPathIsRect(path, pr)) {
  260. NSLog(@"%@", NSStringFromCGRect(*pr));
  261. NSLog(@"same");
  262. } else {
  263. NSLog(@"not");
  264. }
  265. }
  266. }
  267. }
  268. }
  269. CGMutablePathRef createPathForPoints(NSArray* points)
  270. {
  271. CGMutablePathRef path = CGPathCreateMutable();
  272. CGPoint point;
  273. if ([points count] > 0)
  274. {
  275. CGPointMakeWithDictionaryRepresentation((CFDictionaryRef)[points objectAtIndex:0], &point);
  276. CGPathMoveToPoint(path, nil, point.x, point.y);
  277. int i = 1;
  278. while (i < [points count])
  279. {
  280. CGPointMakeWithDictionaryRepresentation((CFDictionaryRef)[points objectAtIndex:i], &point);
  281. CGPathAddLineToPoint(path, nil, point.x, point.y);
  282. i++;
  283. }
  284. CGPathCloseSubpath(path);
  285. }
  286. return path;
  287. }
  288. - (void)gotoSetSecurityOfDevice:(NSString *)QRCode {
  289. NSArray *qrs = [QRCode componentsSeparatedByString:@"|"];
  290. if (!qrs || qrs.count < 3 || ![qrs[1] isEqualToString:@"*_AC_*"]) {//니트 디바이스
  291. [[JDFacade facade] alert:NSLocalizedString(@"서비스 지원장치가 아닙니다", @"서비스 지원장치가 아닙니다")];
  292. return;
  293. }
  294. [self requestQRAuthrize:qrs[0] password:qrs[2]];
  295. }
  296. #pragma mark - UI Events
  297. - (void)btnInsertTouched:(id)sender {
  298. if (!_inputPopup) {
  299. _inputPopup = [[QRCodeInputPopupView alloc] initFromNib];
  300. }
  301. _inputPopup.qrcodeType = _qrcodeType;
  302. _inputPopup.txtActivationCode.text = ksEmptyString;
  303. [_inputPopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
  304. if (buttonIndex == 0) {//OK
  305. [self requestQRAuthrize:_inputPopup.txtActivationCode.text password:_inputPopup.txtPasswd.text];
  306. } else {
  307. if (_avAuthrizationStatus != AVAuthorizationStatusAuthorized) {//카메라 권한이 없을 경우, 리턴,
  308. [self btnCancelTouched:nil];
  309. }
  310. }
  311. }];
  312. }
  313. - (void)btnCancelTouched:(id)sender {
  314. [self dismissViewControllerAnimated:YES completion:nil];
  315. }
  316. #pragma mark - MemoryWarning
  317. - (void)didReceiveMemoryWarning
  318. {
  319. [super didReceiveMemoryWarning];
  320. // Dispose of any resources that can be recreated.
  321. }
  322. @end