BKPasscodeViewController.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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)viewDidAppear:(BOOL)animated
  100. {
  101. [super viewDidAppear: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 = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  119. frame.origin.y += topBarOffset;
  120. frame.size.height -= (topBarOffset + self.keyboardHeight);
  121. self.shiftingView.frame = frame;
  122. }
  123. #pragma mark - Public methods
  124. - (void)setPasscodeStyle:(BKPasscodeInputViewPasscodeStyle)passcodeStyle
  125. {
  126. self.passcodeInputView.passcodeStyle = passcodeStyle;
  127. }
  128. - (BKPasscodeInputViewPasscodeStyle)passcodeStyle
  129. {
  130. return self.passcodeInputView.passcodeStyle;
  131. }
  132. - (void)setKeyboardType:(UIKeyboardType)keyboardType
  133. {
  134. self.passcodeInputView.keyboardType = keyboardType;
  135. }
  136. - (UIKeyboardType)keyboardType
  137. {
  138. return self.passcodeInputView.keyboardType;
  139. }
  140. - (void)showLockMessageWithLockUntilDate:(NSDate *)lockUntil
  141. {
  142. NSTimeInterval timeInterval = [lockUntil timeIntervalSinceNow];
  143. NSUInteger minutes = ceilf(timeInterval / 60.0f);
  144. BKPasscodeInputView *inputView = self.passcodeInputView;
  145. inputView.enabled = NO;
  146. if (minutes == 1) {
  147. inputView.title = NSLocalizedString(@"Try again in 1 minute", nil);
  148. } else {
  149. inputView.title = [NSString stringWithFormat:NSLocalizedString(@"Try again in %d minutes", nil), minutes];
  150. }
  151. NSUInteger numberOfFailedAttempts = [self.delegate passcodeViewControllerNumberOfFailedAttempts:self];
  152. [self showFailedAttemptsCount:numberOfFailedAttempts inputView:inputView];
  153. if (self.lockStateUpdateTimer == nil) {
  154. NSTimeInterval delay = timeInterval + kBKPasscodeOneMinuteInSeconds - (kBKPasscodeOneMinuteInSeconds * (NSTimeInterval)minutes);
  155. self.lockStateUpdateTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:delay]
  156. interval:60.f
  157. target:self
  158. selector:@selector(lockStateUpdateTimerFired:)
  159. userInfo:nil
  160. repeats:YES];
  161. [[NSRunLoop currentRunLoop] addTimer:self.lockStateUpdateTimer forMode:NSDefaultRunLoopMode];
  162. }
  163. }
  164. - (BOOL)lockIfNeeded
  165. {
  166. if (self.currentState != BKPasscodeViewControllerStateCheckPassword) {
  167. return NO;
  168. }
  169. if (NO == [self.delegate respondsToSelector:@selector(passcodeViewControllerLockUntilDate:)]) {
  170. return NO;
  171. }
  172. NSDate *lockUntil = [self.delegate passcodeViewControllerLockUntilDate:self];
  173. if (lockUntil == nil || [lockUntil timeIntervalSinceNow] < 0) {
  174. return NO;
  175. }
  176. [self showLockMessageWithLockUntilDate:lockUntil];
  177. return YES;
  178. }
  179. - (void)updateLockMessageOrUnlockIfNeeded
  180. {
  181. if (self.currentState != BKPasscodeViewControllerStateCheckPassword) {
  182. return;
  183. }
  184. if (NO == [self.delegate respondsToSelector:@selector(passcodeViewControllerLockUntilDate:)]) {
  185. return;
  186. }
  187. BKPasscodeInputView *inputView = self.passcodeInputView;
  188. NSDate *lockUntil = [self.delegate passcodeViewControllerLockUntilDate:self];
  189. if (lockUntil == nil || [lockUntil timeIntervalSinceNow] < 0) {
  190. // invalidate timer
  191. [self.lockStateUpdateTimer invalidate];
  192. self.lockStateUpdateTimer = nil;
  193. [self updatePasscodeInputViewTitle:inputView];
  194. inputView.enabled = YES;
  195. } else {
  196. [self showLockMessageWithLockUntilDate:lockUntil];
  197. }
  198. }
  199. - (void)lockStateUpdateTimerFired:(NSTimer *)timer
  200. {
  201. [self updateLockMessageOrUnlockIfNeeded];
  202. }
  203. - (void)startTouchIDAuthenticationIfPossible
  204. {
  205. [self startTouchIDAuthenticationIfPossible:nil];
  206. }
  207. - (void)startTouchIDAuthenticationIfPossible:(void (^)(BOOL))aCompletionBlock
  208. {
  209. if (NO == [self canAuthenticateWithTouchID]) {
  210. if (aCompletionBlock) {
  211. aCompletionBlock(NO);
  212. }
  213. return;
  214. }
  215. self.promptingTouchID = YES;
  216. [self.touchIDManager loadPasscodeWithCompletionBlock:^(NSString *passcode) {
  217. self.promptingTouchID = NO;
  218. if (passcode) {
  219. self.passcodeInputView.passcode = passcode;
  220. [self passcodeInputViewDidFinish:self.passcodeInputView];
  221. }
  222. if (aCompletionBlock) {
  223. aCompletionBlock(YES);
  224. }
  225. }];
  226. }
  227. #pragma mark - Private methods
  228. - (void)updatePasscodeInputViewTitle:(BKPasscodeInputView *)passcodeInputView
  229. {
  230. switch (self.currentState) {
  231. case BKPasscodeViewControllerStateCheckPassword:
  232. if (self.type == BKPasscodeViewControllerChangePasscodeType) {
  233. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Enter your old password", nil);
  234. else passcodeInputView.title = NSLocalizedString(@"Enter your old passcode", nil);
  235. } else {
  236. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Enter your password", nil);
  237. else passcodeInputView.title = NSLocalizedString(@"Enter your passcode", nil);
  238. }
  239. break;
  240. case BKPasscodeViewControllerStateInputPassword:
  241. if (self.type == BKPasscodeViewControllerChangePasscodeType) {
  242. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Enter your new password", nil);
  243. else passcodeInputView.title = NSLocalizedString(@"Enter your new passcode", nil);
  244. } else {
  245. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Enter a password", nil);
  246. else passcodeInputView.title = NSLocalizedString(@"Enter a passcode", nil);
  247. }
  248. break;
  249. case BKPasscodeViewControllerStateReinputPassword:
  250. if (self.inputViewTitlePassword) passcodeInputView.title = NSLocalizedString(@"Re-enter your password", nil);
  251. else passcodeInputView.title = NSLocalizedString(@"Re-enter your passcode", nil);
  252. break;
  253. default:
  254. break;
  255. }
  256. }
  257. - (void)showFailedAttemptsCount:(NSUInteger)failCount inputView:(BKPasscodeInputView *)aInputView
  258. {
  259. if (failCount == 0) {
  260. if (self.inputViewTitlePassword) aInputView.errorMessage = NSLocalizedString(@"Invalid Password", nil);
  261. else aInputView.errorMessage = NSLocalizedString(@"Invalid Passcode", nil);
  262. } else if (failCount == 1) {
  263. if (self.inputViewTitlePassword) aInputView.errorMessage = NSLocalizedString(@"1 Failed Password Attempt", nil);
  264. else aInputView.errorMessage = NSLocalizedString(@"1 Failed Passcode Attempt", nil);
  265. } else {
  266. if (self.inputViewTitlePassword) aInputView.errorMessage = [NSString stringWithFormat:NSLocalizedString(@"%d Failed Password Attempts", nil), failCount];
  267. else aInputView.errorMessage = [NSString stringWithFormat:NSLocalizedString(@"%d Failed Passcode Attempts", nil), failCount];
  268. }
  269. }
  270. - (void)showTouchIDSwitchView
  271. {
  272. BKTouchIDSwitchView *view = [[BKTouchIDSwitchView alloc] init];
  273. view.delegate = self;
  274. view.touchIDSwitch.on = self.touchIDManager.isTouchIDEnabled;
  275. [self.shiftingView showView:view withDirection:BKShiftingDirectionForward];
  276. }
  277. - (BOOL)canAuthenticateWithTouchID
  278. {
  279. if (NO == [BKTouchIDManager canUseTouchID]) {
  280. return NO;
  281. }
  282. if (self.type != BKPasscodeViewControllerCheckPasscodeType) {
  283. return NO;
  284. }
  285. if (nil == self.touchIDManager || NO == self.touchIDManager.isTouchIDEnabled) {
  286. return NO;
  287. }
  288. if (self.promptingTouchID) {
  289. return NO;
  290. }
  291. #ifndef EXTENSION
  292. if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive) {
  293. return NO;
  294. }
  295. #endif
  296. return YES;
  297. }
  298. #pragma mark - BKPasscodeInputViewDelegate
  299. - (void)passcodeInputViewDidFinish:(BKPasscodeInputView *)aInputView
  300. {
  301. NSString *passcode = aInputView.passcode;
  302. switch (self.currentState) {
  303. case BKPasscodeViewControllerStateCheckPassword:
  304. {
  305. NSAssert([self.delegate respondsToSelector:@selector(passcodeViewController:authenticatePasscode:resultHandler:)],
  306. @"delegate must implement passcodeViewController:authenticatePasscode:resultHandler:");
  307. [self.delegate passcodeViewController:self authenticatePasscode:passcode resultHandler:^(BOOL succeed) {
  308. NSAssert([NSThread isMainThread], @"you must invoke result handler in main thread.");
  309. if (succeed) {
  310. if (self.type == BKPasscodeViewControllerChangePasscodeType) {
  311. self.oldPasscode = passcode;
  312. self.currentState = BKPasscodeViewControllerStateInputPassword;
  313. BKPasscodeInputView *newPasscodeInputView = [self.passcodeInputView copy];
  314. [self customizePasscodeInputView:newPasscodeInputView];
  315. [self updatePasscodeInputViewTitle:newPasscodeInputView];
  316. [self.shiftingView showView:newPasscodeInputView withDirection:BKShiftingDirectionForward];
  317. [self.passcodeInputView becomeFirstResponder];
  318. } else {
  319. [self.delegate passcodeViewController:self didFinishWithPasscode:passcode];
  320. }
  321. } else {
  322. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerDidFailAttempt:)]) {
  323. [self.delegate passcodeViewControllerDidFailAttempt:self];
  324. }
  325. NSUInteger failCount = 0;
  326. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerNumberOfFailedAttempts:)]) {
  327. failCount = [self.delegate passcodeViewControllerNumberOfFailedAttempts:self];
  328. }
  329. [self showFailedAttemptsCount:failCount inputView:aInputView];
  330. // reset entered passcode
  331. aInputView.passcode = nil;
  332. // shake
  333. self.viewShaker = [[AFViewShaker alloc] initWithView:aInputView.passcodeField];
  334. [self.viewShaker shakeWithDuration:0.5f completion:nil];
  335. // lock if needed
  336. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerLockUntilDate:)]) {
  337. NSDate *lockUntilDate = [self.delegate passcodeViewControllerLockUntilDate:self];
  338. if (lockUntilDate != nil) {
  339. [self showLockMessageWithLockUntilDate:lockUntilDate];
  340. }
  341. }
  342. }
  343. }];
  344. break;
  345. }
  346. case BKPasscodeViewControllerStateInputPassword:
  347. {
  348. if (self.type == BKPasscodeViewControllerChangePasscodeType && [self.oldPasscode isEqualToString:passcode]) {
  349. aInputView.passcode = nil;
  350. if (self.inputViewTitlePassword) aInputView.message = NSLocalizedString(@"Enter a different password. Cannot re-use the same password.", nil);
  351. else aInputView.message = NSLocalizedString(@"Enter a different passcode. Cannot re-use the same passcode.", nil);
  352. } else {
  353. self.theNewPasscode = passcode;
  354. self.currentState = BKPasscodeViewControllerStateReinputPassword;
  355. BKPasscodeInputView *newPasscodeInputView = [self.passcodeInputView copy];
  356. [self customizePasscodeInputView:newPasscodeInputView];
  357. [self updatePasscodeInputViewTitle:newPasscodeInputView];
  358. [self.shiftingView showView:newPasscodeInputView withDirection:BKShiftingDirectionForward];
  359. [self.passcodeInputView becomeFirstResponder];
  360. }
  361. break;
  362. }
  363. case BKPasscodeViewControllerStateReinputPassword:
  364. {
  365. if ([passcode isEqualToString:self.theNewPasscode]) {
  366. if (self.touchIDManager && [BKTouchIDManager canUseTouchID]) {
  367. [self showTouchIDSwitchView];
  368. } else {
  369. [self.delegate passcodeViewController:self didFinishWithPasscode:passcode];
  370. }
  371. } else {
  372. self.currentState = BKPasscodeViewControllerStateInputPassword;
  373. BKPasscodeInputView *newPasscodeInputView = [self.passcodeInputView copy];
  374. [self customizePasscodeInputView:newPasscodeInputView];
  375. [self updatePasscodeInputViewTitle:newPasscodeInputView];
  376. if (self.inputViewTitlePassword) newPasscodeInputView.message = NSLocalizedString(@"Password did not match.\nTry again.", nil);
  377. else newPasscodeInputView.message = NSLocalizedString(@"Passcodes did not match.\nTry again.", nil);
  378. [self.shiftingView showView:newPasscodeInputView withDirection:BKShiftingDirectionBackward];
  379. [self.passcodeInputView becomeFirstResponder];
  380. }
  381. break;
  382. }
  383. default:
  384. break;
  385. }
  386. }
  387. #pragma mark - BKTouchIDSwitchViewDelegate
  388. - (void)touchIDSwitchViewDidPressDoneButton:(BKTouchIDSwitchView *)view
  389. {
  390. BOOL enabled = view.touchIDSwitch.isOn;
  391. if (enabled) {
  392. [self.touchIDManager savePasscode:self.theNewPasscode completionBlock:^(BOOL success) {
  393. if (success) {
  394. [self.delegate passcodeViewController:self didFinishWithPasscode:self.theNewPasscode];
  395. } else {
  396. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerDidFailTouchIDKeychainOperation:)]) {
  397. [self.delegate passcodeViewControllerDidFailTouchIDKeychainOperation:self];
  398. }
  399. }
  400. }];
  401. } else {
  402. [self.touchIDManager deletePasscodeWithCompletionBlock:^(BOOL success) {
  403. if (success) {
  404. [self.delegate passcodeViewController:self didFinishWithPasscode:self.theNewPasscode];
  405. } else {
  406. if ([self.delegate respondsToSelector:@selector(passcodeViewControllerDidFailTouchIDKeychainOperation:)]) {
  407. [self.delegate passcodeViewControllerDidFailTouchIDKeychainOperation:self];
  408. }
  409. }
  410. }];
  411. }
  412. }
  413. #pragma mark - Notifications
  414. - (void)didReceiveKeyboardWillShowHideNotification:(NSNotification *)notification
  415. {
  416. CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
  417. /*
  418. #ifdef EXTENSION
  419. self.keyboardHeight = CGRectGetHeight(keyboardRect);
  420. #else
  421. UIInterfaceOrientation statusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  422. self.keyboardHeight = UIInterfaceOrientationIsPortrait(statusBarOrientation) ? CGRectGetWidth(keyboardRect) : CGRectGetHeight(keyboardRect);
  423. #endif
  424. */
  425. self.keyboardHeight = CGRectGetHeight(keyboardRect);
  426. [self.view setNeedsLayout];
  427. }
  428. - (void)didReceiveApplicationWillEnterForegroundNotification:(NSNotification *)notification
  429. {
  430. [self startTouchIDAuthenticationIfPossible];
  431. }
  432. @end