QRCodeViewController.m 14 KB

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