BKPasscodeViewController.m 21 KB

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