Friday, November 28, 2014

TouchID authentication in iOS


#import <LocalAuthentication/LocalAuthentication.h>


- (IBAction)authenicateButtonTapped:(id)sender {
 
  LAContext *context = [[LAContext alloc] init];
 
  NSError *error = nil;
 
  if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
   
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
            localizedReason:@"Are you the device owner?"
                      reply:^(BOOL success, NSError *error) {
                       
                       
                 
              dispatch_async(dispatch_get_main_queue(), ^{
                    // write all your code here
                 
                 
                  if (error) {
                   
                    if(error.code == kLAErrorUserFallback) {
                      [self passcodeFallback];
                    } else if(error.code == kLAErrorUserCancel) {
                      [self cancelLogin];
                    }
                   
                   
                    return;
                   
                  } else {
                 
                      if (success) {
                       
                        [self showAlertWithTitle:@"Success" andMessage:@"You are the device owner!"];

                       
                      } else {
                       
                        [self showAlertWithTitle:@"Error" andMessage:@"You are not the device owner."];

                      }
                  }
               
            });
                       
       }];

  } else {

   
    [self reportError];

   
  }
}


-(void)passcodeFallback {
  [self showAlertWithTitle:@"Error" andMessage:@"Show UI Screen to retrieve passcode from keychain"];

}

-(void)cancelLogin {
  [self showAlertWithTitle:@"Error" andMessage:@"Login Cancelled"];

}

-(void)reportError {
  [self showAlertWithTitle:@"Error" andMessage:@"Your deivice can't be authenticated"];
}


-(void)showAlertWithTitle:(NSString *)aTitle andMessage:(NSString *)aMsg {
 
 
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:aTitle
                                                  message:aMsg
                                                 delegate:nil
                                        cancelButtonTitle:@"Ok"
                                        otherButtonTitles:nil];
  [alert show];
 
}

No comments: