BKPasscodeViewController.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. //
  2. // BKPasscodeViewController.m
  3. // BKPasscodeViewDemo
  4. //
  5. // Created by Byungkook Jang on 2014. 4. 20..
  6. // Copyright (c) 2014년 Byungkook Jang. All rights reserved.
  7. //
  8. #import "BKPasscodeViewController.h"
  9. #import "BKShiftingView.h"
  10. #import "AFViewShaker.h"
  11. #import "BKPasscodeUtils.h"
  12. typedef enum : NSUInteger {
  13. BKPasscodeViewControllerStateUnknown,
  14. BKPasscodeViewControllerStateCheckPassword,
  15. BKPasscodeViewControllerStateInputPassword,
  16. BKPasscodeViewControllerStateReinputPassword
  17. } BKPasscodeViewControllerState;
  18. #define kBKPasscodeOneMinuteInSeconds (60)
  19. #define kBKPasscodeDefaultKeyboardHeight (216)
  20. @interface BKPasscodeViewController ()
  21. @property (nonatomic, strong) BKShiftingView *shiftingView;
  22. @property (nonatomic) BKPasscodeViewControllerState currentState;
  23. @property (nonatomic, strong) NSString *oldPasscode;
  24. @property (nonatomic, strong) NSString *theNewPasscode;
  25. @property (nonatomic, strong) NSTimer *lockStateUpdateTimer;
  26. @property (nonatomic) CGFloat keyboardHeight;
  27. @property (nonatomic, strong) AFViewShaker *viewShaker;
  28. @property (nonatomic) BOOL promptingTouchID;
  29. @end
  30. @implementation BKPasscodeViewController
  31. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  32. {
  33. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  34. if (self) {
  35. // init state
  36. _type = BKPasscodeViewControllerNewPasscodeType;
  37. _currentState = BKPasscodeViewControllerStateInputPassword;
  38. // create shifting view
  39. self.shiftingView = [[BKShiftingView alloc] init];
  40. self.shiftingView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  41. self.shiftingView.currentView = [self instantiatePasscodeInputView];
  42. // keyboard notifications
  43. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardWillShowHideNotification:) name:UIKeyboardWillShowNotification object:nil];
  44. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardWillShowHideNotification:) name:UIKeyboardWillHideNotification object:nil];
  45. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveApplicationWillEnterForegroundNotification:)
  46. name:UIApplicationWillEnterForegroundNotification
  47. object:nil];
  48. self.keyboardHeight = kBKPasscodeDefaultKeyboardHeight; // sometimes keyboard notification is not posted at all. so setting default value.
  49. }
  50. return self;
  51. }
  52. - (void)dealloc
  53. {
  54. [self.lockStateUpdateTimer invalidate];
  55. self.lockStateUpdateTimer = nil;
  56. [[NSNotificationCenter defaultCenter] removeObserver:self];
  57. }
  58. - (void)setType:(BKPasscodeViewControllerType)type
  59. {
  60. if (_type == type) {
  61. return;
  62. }
  63. _type = type;
  64. switch (type) {
  65. case BKPasscodeViewControllerNewPasscodeType:
  66. self.currentState = BKPasscodeViewControllerStateInputPassword;
  67. break;
  68. default:
  69. self.currentState = BKPasscodeViewControllerStateCheckPassword;
  70. break;
  71. }
  72. }
  73. - (BKPasscodeInputView *)passcodeInputView
  74. {
  75. if (NO == [self.shiftingView.currentView isKindOfClass:[BKPasscodeInputView class]]) {
  76. return nil;
  77. }
  78. return (BKPasscodeInputView *)self.shiftingView.currentView;
  79. }
  80. - (BKPasscodeInputView *)instantiatePasscodeInputView
  81. {
  82. BKPasscodeInputView *view = [[BKPasscodeInputView alloc] init];
  83. view.delegate = self;
  84. view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  85. return view;
  86. }
  87. - (void)customizePasscodeInputView:(BKPasscodeInputView *)aPasscodeInputView
  88. {
  89. }
  90. - (void)viewDidLoad
  91. {
  92. [super viewDidLoad];
  93. [self.view setBackgroundColor:[UIColor colorWithRed:0.94 green:0.94 blue:0.96 alpha:1]];
  94. [self updatePasscodeInputViewTitle:self.passcodeInputView];
  95. [self customizePasscodeInputView:self.passcodeInputView];
  96. [self.view addSubview:self.shiftingView];
  97. [self lockIfNeeded];
  98. }
  99. - (void)viewWillAppear:(BOOL)animated
  100. {
  101. [super viewWillAppear:animated];
  102. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  103. if (self.passcodeInputView.isEnabled) {
  104. [self startTouchIDAuthenticationIfPossible];
  105. }
  106. [self.passcodeInputView becomeFirstResponder];
  107. });
  108. }
  109. - (void)viewWillDisappear:(BOOL)animated
  110. {
  111. [super viewWillDisappear:animated];
  112. [self.view endEditing:YES];
  113. }
  114. - (void)viewDidLayoutSubviews
  115. {
  116. [super viewDidLayoutSubviews];
  117. CGRect frame = self.view.bounds;
  118. CGFloat topBarOffset = 0;
  119. if ([self respondsToSelector:@selector(topLayoutGuide)]) {
  120. topBarOffset = [self.topLayoutGuide length];
  121. }
  122. frame.origin.y += topBarOffset;
  123. frame.size.height -= (topBarOffset + self.keyboardHeight);
  124. self.shiftingView.frame = frame;
  125. }
  126. #pragma mark - Public methods
  127. - (void)setPasscodeStyle:(BKPasscodeInputViewPasscodeStyle)passcodeStyle
  128. {
  129. self.passcodeInputView.passcodeStyle = passcodeStyle;
  130. }
  131. - (BKPasscodeInputViewPasscodeStyle)passcodeStyle
  132. {
  133. return self.passcodeInputView.passcodeStyle;
  134. }
  135. - (void)setKeyboardType:(UIKeyboardType)keyboardType
  136. {
  137. self.passcodeInputView.keyboardType = keyboardType;
  138. }
  139. - (UIKeyboardType)keyboardType
  140. {
  141. return self.passcodeInputView.keyboardType;
  142. }
  143. - (void)showLockMessageWithLockUntilDate:(NSDate *)lockUntil
  144. {
  145. NSTimeInterval timeInterval = [lockUntil timeIntervalSinceNow];
  146. NSUInteger minutes = ceilf(timeInterval / 60.0f);
  147. BKPasscodeInputView *inputView = self.passcodeInputView;
  148. inputView.enabled = NO;
  149. if (minutes == 1) {
  150. inputView.title = NSLocalizedString(@"Try again in 1 minute", nil);
  151. } else {
  152. inputView.title = [NSString stringWithFormat:NSLocalizedString(@"Try again in %d minutes", nil), minutes];
  153. }
  154. NSUInteger numberOfFailedAttempts = [self.delegate passcodeViewControllerNumberOfFailedAttempts:self];
  155. [self showFailedAttemptsCount:numberOfFailedAttempts inputView:inputView];
  156. if (self.lockStateUpdateTimer == nil) {
  157. NSTimeInterval delay = timeInterval + kBKPasscodeOneMinuteInSeconds - (kBKPasscodeOneMinuteInSeconds * (NSTimeInterval)minutes);
  158. self.lockStateUpdateTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:delay]
  159. interval:60.f
  160. target:self
  161. selector:@selector(lockStateUpdateTimerFired:)
  162. userInfo:nil
  163. repeats:YES];
  164. [[NSRunLoop currentRunLoop] addTimer:self.lockStateUpdateTimer forMode:NSDefaultRunLoopMode];
  165. }
  166. }
  167. - (BOOL)lockIfNeeded
  168. {
  169. if (self.currentState != BKPasscodeViewControllerStateCheckPassword) {
  170. return NO;
  171. }
  172. if (NO == [self.delegate respondsToSelector:@selector(passcodeViewControllerLockUntilDate:)]) {
  173. return NO;
  174. }
  175. NSDate *lockUntil = [self.delegate passcodeViewControllerLockUntilDate:self];
  176. if (lockUntil == nil || [lockUntil timeIntervalSinceNow] < 0) {
  177. return NO;
  178. }
  179. [self showLockMessageWithLockUntilDate:lockUntil];
  180. return YES;
  181. }
  182. - (void)updateLockMessageOrUnlockIfNeeded
  183. {
  184. if (self.currentState != BKPasscodeViewControllerStateCheckPassword) {
  185. return;
  186. }
  187. if (NO == [self.delegate respondsToSelector:@selector(passcodeViewControllerLockUntilDate:)]) {
  188. return;
  189. }
  190. BKPasscodeInputView *inputView = self.passcodeInputView;
  191. NSDate *lockUntil = [self.delegate passcodeViewControllerLockUntilDate:self];
  192. if (lockUntil == nil || [lockUntil timeIntervalSinceNow] < 0) {
  193. // invalidate timer
  194. [self.lockStateUpdateTimer invalidate];
  195. self.lockStateUpdateTimer = nil;
  196. [self updatePasscodeInputViewTitle:inputView];
  197. inputView.enabled = YES;
  198. } else {
  199. [self showLockMessageWithLockUntilDate:lockUntil];
  200. }
  201. }
  202. - (void)lockStateUpdateTimerFired:(NSTimer *)timer
  203. {
  204. [self updateLockMessageOrUnlockIfNeeded];
  205. }
  206. - (void)startTouchIDAuthenticationIfPossible
  207. {
  208. [self startTouchIDAuthenticationIfPossible:nil];
  209. }
  210. - (void)startTouchIDAuthenticationIfPossible:(void (^)(BOOL))aCompletionBlock
  211. {
  212. if (NO == [self canAuthenticateWithTouchID]) {
  213. if (aCompletionBlock) {
  214. aCompletionBlock(NO);
  215. }
  216. return;
  217. }
  218. self.promptingTouchID = YES;
  219. [self.touchIDManager loadPasscodeWithCompletionBlock:^(NSString *passcode) {
  220. self.promptingTouchID = NO;
  221. if (passcode) {
  222. self.passcodeInputView.passcode = passcode;
  223. [self passcodeInputViewDidFinish:self.passcodeInputView];
  224. }
  225. if (aCompletionBlock) {
  226. aCompletionBlock(YES);
  227. }
  228. }];
  229. }
  230. #pragma mark - Private methods
  231. - (void)updatePasscodeInputViewTitle:(BKPasscodeInputView *)passcodeInputView
  232. {
  233. switch (self.currentState) {
  234. case BKPasscodeViewControllerStateCheckPassword:
  235. if (self.type == BKPasscodeViewControllerChangePasscodeType) {
  236. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Enter your old password", nil);
  237. else passcodeInputView.title = NSLocalizedString(@"Enter your old passcode", nil);
  238. } else {
  239. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Enter your password", nil);
  240. else passcodeInputView.title = NSLocalizedString(@"Enter your passcode", nil);
  241. }
  242. break;
  243. case BKPasscodeViewControllerStateInputPassword:
  244. if (self.type == BKPasscodeViewControllerChangePasscodeType) {
  245. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Enter your new password", nil);
  246. else passcodeInputView.title = NSLocalizedString(@"Enter your new passcode", nil);
  247. } else {
  248. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Enter a password", nil);
  249. else passcodeInputView.title = NSLocalizedString(@"Enter a passcode", nil);
  250. }
  251. break;
  252. case BKPasscodeViewControllerStateReinputPassword:
  253. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Re-enter your password", nil);
  254. else passcodeInputView.title = NSLocalizedString(@"Re-enter your passcode", nil);
  255. break;
  256. default:
  257. break;
  258. }
  259. }
  260. - (void)showFailedAttemptsCount:(NSUInteger)failCount inputView:(BKPasscodeInputView *)aInputView
  261. {
  262. if (failCount == 0) {
  263. if (self.inputViewTitlePassword) aInputView.errorMessage = NSLocalizedString(@"Invalid Password", nil);
  264. else aInputView.errorMessage = NSLocalizedString(@"Invalid Passcode", nil);
  265. } else if (failCount == 1) {
  266. if (self.inputViewTitlePassword) aInputView.errorMessage = NSLocalizedString(@"1 Failed Password Attempt", nil);
  267. else aInputView.errorMessage = NSLocalizedString(@"1 Failed Passcode Attempt", nil);
  268. } else {
  269. if (self.inputViewTitlePassword) aInputView.errorMessage = [NSString stringWithFormat:NSLocalizedString(@"%d Failed Password Attempts", nil), failCount];
  270. else aInputView.errorMessage = [NSString stringWithFormat:NSLocalizedString(@"%d Failed Passcode Attempts", nil), failCount];
  271. }
  272. }
  273. - (void)showTouchIDSwitchView
  274. {
  275. BKTouchIDSwitchView *view = [[BKTouchIDSwitchView alloc] init];
  276. view.delegate = self;
  277. view.touchIDSwitch.on = self.touchIDManager.isTouchIDEnabled;
  278. [self.shiftingView showView:view withDirection:BKShiftingDirectionForward];
  279. }
  280. - (BOOL)canAuthenticateWithTouchID
  281. {
  282. if (NO == [BKTouchIDManager canUseTouchID]) {
  283. return NO;
  284. }
  285. if (self.type != BKPasscodeViewControllerCheckPasscodeType) {
  286. return NO;
  287. }
  288. if (nil == self.touchIDManager || NO == self.touchIDManager.isTouchIDEnabled) {
  289. return NO;
  290. }
  291. if (self.promptingTouchID) {
  292. return NO;
  293. }
  294. #ifndef EXTENSION
  295. if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive) {
  296. return NO;
  297. }
  298. #endif
  299. return YES;
  300. }
  301. #pragma mark - BKPasscodeInputViewDelegate
  302. - (void)passcodeInputViewDidFinish:(BKPasscodeInputView *)aInputView
  303. {
  304. NSString *passcode = aInputView.passcode;
  305. switch (self.currentState) {
  306. case BKPasscodeViewControllerStateCheckPassword:
  307. {
  308. NSAssert([self.delegate respondsToSelector:@selector(passcodeViewController:authenticatePasscode:resultHandler:)],
  309. @"delegate must implement passcodeViewController:authenticatePasscode:resultHandler:");
  310. [self.delegate passcodeViewController:self authenticatePasscode:passcode resultHandler:^(BOOL succeed) {
  311. NSAssert([NSThread isMainThread], @"you must invoke result handler in main thread.");
  312. if (succeed) {
  313. if (self.type == BKPasscodeViewControllerChangePasscodeType) {
  314. self.oldPasscode = passcode;
  315. self.currentState = BKPasscodeViewControllerStateInputPassword;
  316. BKPasscodeInputView *newPasscodeInputView = [self.passcodeInputView copy];
  317. [self customizePasscodeInputView:newPasscodeInputView];
  318. [self updatePasscodeInputViewTitle:newPasscodeInputView];
  319. [self.shiftingView showView:newPasscodeInputView withDirection:BKShiftingDirectionForward];
  320. [self.passcodeInputView becomeFirstResponder];
  321. } else {
  322. [self.delegate passcodeViewController:self didFinishWithPasscode:passcode];
  323. }
  324. } else {
  325. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerDidFailAttempt:)]) {
  326. [self.delegate passcodeViewControllerDidFailAttempt:self];
  327. }
  328. NSUInteger failCount = 0;
  329. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerNumberOfFailedAttempts:)]) {
  330. failCount = [self.delegate passcodeViewControllerNumberOfFailedAttempts:self];
  331. }
  332. [self showFailedAttemptsCount:failCount inputView:aInputView];
  333. // reset entered passcode
  334. aInputView.passcode = nil;
  335. // shake
  336. self.viewShaker = [[AFViewShaker alloc] initWithView:aInputView.passcodeField];
  337. [self.viewShaker shakeWithDuration:0.5f completion:nil];
  338. // lock if needed
  339. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerLockUntilDate:)]) {
  340. NSDate *lockUntilDate = [self.delegate passcodeViewControllerLockUntilDate:self];
  341. if (lockUntilDate != nil) {
  342. [self showLockMessageWithLockUntilDate:lockUntilDate];
  343. }
  344. }
  345. }
  346. }];
  347. break;
  348. }
  349. case BKPasscodeViewControllerStateInputPassword:
  350. {
  351. if (self.type == BKPasscodeViewControllerChangePasscodeType && [self.oldPasscode isEqualToString:passcode]) {
  352. aInputView.passcode = nil;
  353. if (self.inputViewTitlePassword) aInputView.message = NSLocalizedString(@"Enter a different password. Cannot re-use the same password.", nil);
  354. else aInputView.message = NSLocalizedString(@"Enter a different passcode. Cannot re-use the same passcode.", nil);
  355. } else {
  356. self.theNewPasscode = passcode;
  357. self.currentState = BKPasscodeViewControllerStateReinputPassword;
  358. BKPasscodeInputView *newPasscodeInputView = [self.passcodeInputView copy];
  359. [self customizePasscodeInputView:newPasscodeInputView];
  360. [self updatePasscodeInputViewTitle:newPasscodeInputView];
  361. [self.shiftingView showView:newPasscodeInputView withDirection:BKShiftingDirectionForward];
  362. [self.passcodeInputView becomeFirstResponder];
  363. }
  364. break;
  365. }
  366. case BKPasscodeViewControllerStateReinputPassword:
  367. {
  368. if ([passcode isEqualToString:self.theNewPasscode]) {
  369. if (self.touchIDManager && [BKTouchIDManager canUseTouchID]) {
  370. [self showTouchIDSwitchView];
  371. } else {
  372. [self.delegate passcodeViewController:self didFinishWithPasscode:passcode];
  373. }
  374. } else {
  375. self.currentState = BKPasscodeViewControllerStateInputPassword;
  376. BKPasscodeInputView *newPasscodeInputView = [self.passcodeInputView copy];
  377. [self customizePasscodeInputView:newPasscodeInputView];
  378. [self updatePasscodeInputViewTitle:newPasscodeInputView];
  379. if (self.inputViewTitlePassword) newPasscodeInputView.message = NSLocalizedString(@"Password did not match.\nTry again.", nil);
  380. else newPasscodeInputView.message = NSLocalizedString(@"Passcodes did not match.\nTry again.", nil);
  381. [self.shiftingView showView:newPasscodeInputView withDirection:BKShiftingDirectionBackward];
  382. [self.passcodeInputView becomeFirstResponder];
  383. }
  384. break;
  385. }
  386. default:
  387. break;
  388. }
  389. }
  390. #pragma mark - BKTouchIDSwitchViewDelegate
  391. - (void)touchIDSwitchViewDidPressDoneButton:(BKTouchIDSwitchView *)view
  392. {
  393. BOOL enabled = view.touchIDSwitch.isOn;
  394. if (enabled) {
  395. [self.touchIDManager savePasscode:self.theNewPasscode completionBlock:^(BOOL success) {
  396. if (success) {
  397. [self.delegate passcodeViewController:self didFinishWithPasscode:self.theNewPasscode];
  398. } else {
  399. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerDidFailTouchIDKeychainOperation:)]) {
  400. [self.delegate passcodeViewControllerDidFailTouchIDKeychainOperation:self];
  401. }
  402. }
  403. }];
  404. } else {
  405. [self.touchIDManager deletePasscodeWithCompletionBlock:^(BOOL success) {
  406. if (success) {
  407. [self.delegate passcodeViewController:self didFinishWithPasscode:self.theNewPasscode];
  408. } else {
  409. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerDidFailTouchIDKeychainOperation:)]) {
  410. [self.delegate passcodeViewControllerDidFailTouchIDKeychainOperation:self];
  411. }
  412. }
  413. }];
  414. }
  415. }
  416. #pragma mark - Notifications
  417. - (void)didReceiveKeyboardWillShowHideNotification:(NSNotification *)notification
  418. {
  419. CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
  420. /*
  421. #ifdef EXTENSION
  422. self.keyboardHeight = CGRectGetHeight(keyboardRect);
  423. #else
  424. UIInterfaceOrientation statusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  425. self.keyboardHeight = UIInterfaceOrientationIsPortrait(statusBarOrientation) ? CGRectGetWidth(keyboardRect) : CGRectGetHeight(keyboardRect);
  426. #endif
  427. */
  428. self.keyboardHeight = CGRectGetHeight(keyboardRect);
  429. [self.view setNeedsLayout];
  430. }
  431. - (void)didReceiveApplicationWillEnterForegroundNotification:(NSNotification *)notification
  432. {
  433. [self startTouchIDAuthenticationIfPossible];
  434. }
  435. @end