Академический Документы
Профессиональный Документы
Культура Документы
Code
Categories LearningGuides
IOS 8
iOS8:IntegratingTouchID
byJoshSephton 17Sep2014
16Comments
60 150 18
InSeptember2013,AppleunveiledthelatestiPhonewitharangeofhardware
improvements.ThemostinnovativefeatureofiPhone5swasathinmetalband
surroundingthehomebutton,afingerprintsensorcalledTouchID.Developers
clamberedtoknowabouttheAPI.AyearonandiOS8introducesanewframework
givingdeveloperstheabilitytousethefingerprintsensor.
TheLocalAuthenticationframeworkprovidesmethodstopromptauserto
authenticate.Youcouldusethisasaloginforyourapporuseitjusttoprotect
sensitivedatawithinanapp.Inthistutorial,Iwillexplaintheoptionsavailabletoyou,
whatdatayoucangetfromthedevice,andwellalsobuildasampleapp.
ThistutorialrequiresXcode6tocreatetheprojectandyoullneedadevicewith
TouchIDtotestthesampleappthatwe'llcreate.
1.TouchID
TouchIDreferstothefingerprintsensorbuiltintothehomebuttonofiPhone5s.It
wasaddedtohelpencouragetheuseofpasscodesbymakingiteasierforusersto
authenticate.Youcanconfigureeachdevicewithamaximumoffivefingerprints.Up
tonow,ithasbeenusedtounlockthedeviceandtomakepurchasesintheiTunes
Store,AppStore,andiBooksStore.Beforeweseehowyoumightuseitinyour
apps,here'saquickoverviewofthesensoritself.
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 1/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
TheTouchIDsensorisabletoscanyourfingersataresolutionof500pixelsper
inch,allowingittoputeachprintintooneofthreecategories,arch,whorl,orloop.
Thesensorisdesignedtobetrulyconvenient,youcanscanyourfingerinany
orientationandit'lldetermineamatchwithanyexistingfingerprintregardlessofthe
originalorientation.
Appleclaimthattheoddsofafalsepositiveforagivenfingerprintis1in50,000,
whichismuchbetterthantheoddsofguessinga4digitpincodeat1in10,000.
Theydon'tmentionthatit'spossibletofallbacktousingthepinnumberfortimes
whenyou'renotabletouseyourfingerprints,forexample,whenyou'reallwrinkly
afterswimming.
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 2/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
IfyouplantouseTouchID,thenit'simportantthatyoutooconsiderscenarioswhere
userscan'tusetheirfingerasameanstoauthenticate.Becauseyou'renotableto
verifyagainstthedevice'spincodeasAppledo,itmaybeagoodideatohaveusers
createapasswordwithinyourapp.
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 3/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
2.SecurityConsiderations
Thebiggestconcernwiththefingerprintsensoristhatusers'sprivacyis
fundamentallybreached.Ifyourpasswordisrevealed,youcanchangeitto
somethingnewandamaliciouspersonwouldnolongerbeabletouseittoaccess
yourdata.Ifyourfingerprint,orApple'smathematicalrepresentationofit,is
exposed,youcan'tchangeitquitesoeasily.
TheLocalAuthenticationframeworkhandlesalloftheheavyliftingofverifying
users.WhenworkingwithTouchID,it'simportanttoknowthatitrevealsnodetails
abouttheuserandnodataistransferredfromthedevice.However,developerscan
usetheframeworktocheckifauserisallowedtousetheapp.
Ifyou'refamiliarwiththeOAuthspecification,youmayseesimilaritiesintheway
authenticationishandled,youaskathirdpartytoverifytheidentifyofauser,ifyou
trustthethirdparty,youcanusetheirresponseinplaceofrequestingcredentials
directlyfromtheuser.
3. LAContext
Iftheframeworkisunabletoauthenticate,itthrowsanerror.Thereareseveral
reasonswhyadeviceisn'tabletoauthenticate.
LAErrorTouchIDNotAvailable Thedevicedoesn'thaveafingerprintsensor.
LAErrorPasscodeNotSet Thereisnopasscodesetonthedevice,whichmeans
thatTouchIDisdisabled.
LAErrorTouchIDNotEnrolled Thereisapasscodesetbutthedevicehasnot
beenconfiguredwithanyfingerprints.
Ifanerroristhrownwithanyoftheaboveerrorcodes,thenyouneedtoprovide
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 4/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
someothermethodforuserstoauthenticate.Atthispoint,youcan'trelysolelyon
TouchID.
Let'screateasampleapptolearnhowwecanmakeuseoftheLocalAuthentication
framework.
4.ProjectSetup
Step1
OpenXcodeandselectNew>Project...fromtheFilemenu.ChooseSingleView
ApplicationfromthelistofiOSApplicationtemplatesandclickNext.
Step2
Enteranameforyourproject,I'vecalledmineAuth.Enteryourorganization's
name,companyidentifier,andclassprefix.ChooseiPhonefromtheDeviceslist,
clickNext,andchoosealocationtosavetheproject.
Step3
ClickViewController.handdefineanewaction, authenticateButtonTapped ,which
willtriggertheauthenticationprocess.Theinterfaceofthe ViewController class
shouldlooklikethis:
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 5/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
1 #import<UIKit/UIKit.h>
2
3 @interfaceViewController:UIViewController
4
5 (IBAction)authenticateButtonTapped:(id)sender;
6
7 @end
Step4
OpenMain.storyboardanddragaButtonontotheviewcontroller'sview.Change
thebuttonlabeltoreadAuthenticate.
Step5
RightclickthebuttontoshowtheConnectionsInspector.Clicktheplusontheleft
oftheTouchUpInsideeventandselecttheviewcontrollerthatcontainsthebutton.
Anothermenuwillappearinwhichyoucanselecttheactionwedeclaredamoment
ago.
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 6/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
5.AuthenticateaUser
Step1
SwitchtoViewController.mtoimplementthe authenticateButtonTapped method.
AtthetopofthefileaddthefollowingimportstatementfortheLocalAuthentication
framework.
1 #import<LocalAuthentication/LocalAuthentication.h>
Step2
Inthe authenticateButtonTapped method,wecreateacontextanddetermineifthe
contextcanevaluatethe LAPolicyDeviceOwnerAuthenticationWithBiometrics policy,
otherwiseshowanerrormessage.
01 (IBAction)authenticateButtonTapped:(id)sender{
02 LAContext*context=[[LAContextalloc]init];
03
04 NSError*error=nil;
05
06 if([contextcanEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
07 //AuthenticateUser
08
09 }else{
10
11 UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"Error"
12 message:@"Yourdevicecannot
13 delegate:nil
14 cancelButtonTitle:@"Ok"
15 otherButtonTitles:nil];
16 [alertshow];
17
18 }
19 }
Step3
Ifthe LAContext objectisabletoauthenticateusingTouchID,thenwetrytoverify
theuser'sidentity.Ifnoerroristhrown,wetelltheuseriftheyaretheownerofthe
device.Thefinalimplementationofthe authenticateButtonTapped methodisshown
below.
01 (void)authenicateButtonTapped:(id)sender{
02 LAContext*context=[[LAContextalloc]init];
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 7/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
03
04 NSError*error=nil;
05 if([contextcanEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
06 [contextevaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
07 localizedReason:@"Areyouthedeviceowner?"
08 reply:^(BOOLsuccess,NSError*error){
09
10 if(error){
11 UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"Error"
12 message:@"Therewasa
13 delegate:nil
14 cancelButtonTitle:@"Ok"
15 otherButtonTitles:nil
16 [alertshow];
17 return;
18 }
19
20 if(success){
21 UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"Success"
22 message:@"Youarethe
23 delegate:nil
24 cancelButtonTitle:@"Ok"
25 otherButtonTitles:nil
26 [alertshow];
27
28 }else{
29 UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"Error"
30 message:@"Youarenot
31 delegate:nil
32 cancelButtonTitle:@"Ok"
33 otherButtonTitles:nil
34 [alertshow];
35 }
36
37 }];
38
39 }else{
40
41 UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"Error"
42 message:@"Yourdevicecannot
43 delegate:nil
44 cancelButtonTitle:@"Ok"
45 otherButtonTitles:nil];
46 [alertshow];
47
48 }
49 }
6.BuildandRun
Buildandruntheapplicationonaphysicaldevicewithafingerprintsensorandtap
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 8/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
thebuttontoauthenticate.AslongasyourdevicehasTouchIDsupport,youshould
bepromptedtoauthenticate.Ifyouputyourfingeronthesensor,theappshouldtell
youifyou'rethedeviceownerornot.
Conclusion
Inthistutorial,welookedattheLocalAuthenticationframeworkintroducediniOS8.
Bycheckingtheidentityoftheauthenticatinguser,the LAContext classallowsusers
toidentifythemselveswithoutprovidingsensitivedatadirectlytotheapp.
Difficulty:
Beginner
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 9/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
Length:
Medium
Categories:
TranslationsAvailable:
Tuts+tutorialsaretranslatedbyourcommunitymembers.Ifyou'dliketotranslatethispostintoanotherlanguage,
letusknow!
ViewonGithub
AboutJoshSephton
Joshworksat383(http://383project.com/),helpingambitiousclientscreateopportunitythrough
innovation.Webelievethatnewtechnology,newcategorycompetitionfromstartupsandnewcustomer
behaviourshouldbechanginghoworganisation'sareoperating.
SuggestedTuts+Course
MultiPlatformAppsInC#WithXamarin Start
RelatedTutorials
UsingAlterEgotoAddTwoFactorAuthenticationtoYourWordPressSite
Code
CoreDatafromScratch:MoreNSFetchedResultsController
Code
CoreDatafromScratch:NSFetchedResultsController
Code
Jobs
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 10/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
WordPressDeveloper
atPlacemarkDigitalinMelbourneVIC,Australia
WebDesignInstructor
atTuts+inMelbourneVIC,Australia
Jointhediscussion
BarathanKulothongan 3monthsago
GreatArticle!,Ihaveonequestiononhowtomatchwhichuserisactuallyswipingthe
finger?HowdowematchtheTouchIDtoUser?pleaseadvise.
5 Reply Share
eggman33 2monthsago
IsthereanywaytobenotifiedtheTouchIDsensorisbeingtouched?Nodataneeded,just
needtoknowaneventoccurred.
2 Reply Share
BijuUIDeveloper:www.bijudes 2monthsago
GreatArticle:)
1 Reply Share
MarioGhersi amonthago
Whytakesalotoftimetoappearsthemessages?MaybebecauseisiPhone5S?(10to16
seconds!)
Reply Share
Fahad>RicardoFunk 16daysago
Becausethealertviewisshownonthebackgroundthread,getthemain
threadandshowalertviewonit.
dispatch_async(dispatch_get_main_queue(),^{
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 11/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
dispatch_async(dispatch_get_main_queue(),^{
//AlertViewCode
})
1 Reply Share
KennethR.Lewis amonthago
Sowiththissystemwetotallyhavetoacceptit'svalidbutthatmeanswehavetosaveour
passwordinthekeychainorsomewheresecurethatwecanusesotheydon'thaveto
enteritmanuallycorrect?Whatwouldbethebestsolutionforsecuritywhenyouare
successfultoretrievethepasswordandusingthatpassword.Justthinkingoutloudfrom
thestandpointofjailbrokendevicesandsecurityastowhatisthemostsecurewaysothat
thepasswordisnotcompromised.
Reply Share
KennethR.Lewis>KennethR.Lewis amonthago
Afterreadingdiscussionsfrom1Passwordthatisexactlywhatyouhavetodo.:)
Reply Share
KennethR.Lewis amonthago
IseethatweshouldalsobeusingthecodeoftheNSErrortodeterminehowwehandle
thingstoo:
LAErrorAuthenticationFailed=kLAErrorAuthenticationFailed,
///Authenticationwascanceledbyuser(e.g.tappedCancelbutton).
LAErrorUserCancel=kLAErrorUserCancel,
///Authenticationwascanceled,becausetheusertappedthefallbackbutton(Enter
Password).
LAErrorUserFallback=kLAErrorUserFallback,
///Authenticationwascanceledbysystem(e.g.anotherapplicationwenttoforeground).
LAErrorSystemCancel=kLAErrorSystemCancel,
///Authenticationcouldnotstart,becausepasscodeisnotsetonthedevice.
LAErrorPasscodeNotSet=kLAErrorPasscodeNotSet,
///Authenticationcouldnotstart,becauseTouchIDisnotavailableonthedevice.
LAErrorTouchIDNotAvailable=kLAErrorTouchIDNotAvailable,
///Authenticationcouldnotstart,becauseTouchIDhasnoenrolledfingers.
LAErrorTouchIDNotEnrolled=kLAErrorTouchIDNotEnrolled,
Reply Share
ramanan amonthago
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 12/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
ramanan
SimpleandNeatCoding!Superb.
Reply Share
MichalGreg 2monthsago
Whenipresson"EnterPassword"fromtheoutputpopup,itdoesnothing.
Howtosendtheusertoapasswordenteringscreenwhenheclickson"EnterPassword"?
Itriedfallbackmechanismasfollowbutnothingworked
[myContextevaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:myLocalizedReasonString
reply:^(BOOLsucces,NSError*error){
if(succes){
NSLog(@"Userisauthenticatedsuccessfully")
}else{
switch(error.code){
caseLAErrorAuthenticationFailed:
NSLog(@"AuthenticationFailed")
break
caseLAErrorUserCancel:
seemore
Reply Share
KennethR.Lewis>MichalGreg amonthago
Whatyouwanttodoisloadyourpassworddialogandthenmakethecallusing
LAContext.
IhadcreatedacheckTouchIDthatiscalledafterthecontrolsareloadedinmy
passworddialogafterviewDidAppear:
Hopethishelps.
(IBAction)btnTouchIDClicked:(id)sender{
__loadedTouchID=FALSE
[selfcheckTouchID]
}
staticBOOL__loadedTouchID=FALSE
(void)checkTouchID{
MAINTHREAD_SOMETHING(checkTouchID)
self.successTouchID=FALSE
if(__loadedTouchID){
return
seemore
Reply Share
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 13/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
Reply Share
KennethR.Lewis>MichalGreg amonthago
YouneedtolookatthecodeoftheErrortoknowtheyclickedEnterPassword
whichiskLAErrorUserFallbackandatthatpointyouwouldsimplysetfocustoyour
textcontrolforthepassword.
Reply Share
MichalGreg>KennethR.Lewis amonthago
Yes,thatisfine.WhenkLAErrorUserFallbackoccours,icanshowapopup
textfieldforenteringthetouchidpassword.Butonsubmittingit,whichisthe
methodtoverifyifuserenteredcorrectpassword?
Reply Share
KennethR.Lewis>MichalGreg amonthago
Yousimplylookatsuccessintheblockmeaningyousuccessfully
validatedyourselfwithyourfingerprint.Soatthatpointyouwould
retrieveyoursecurepasswordfromthekeychainhoweveryou
storeditandunlockyourappasifyoutypeditin.
TouchIDwon'tbestoringyourpasswordorretrievingit.Itsimplylets
Teachingskillstomillionsworldwide.
FollowUs
HelpandSupport
FAQ
TermsofUse
ContactSupport
AboutTuts+
Advertise
TeachatTuts+
EmailNewsletters
GetTuts+updates,news,surveys&
offers.
Subscribe
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 14/15
12/4/2014 iOS8:IntegratingTouchIDTuts+CodeTutorial
Subscribe
PrivacyPolicy
Customdigitalserviceslikelogodesign,WordPressinstallation,video
productionandmore.
CheckoutEnvatoStudio
Addmorefeaturestoyourwebsitesuchasuserprofiles,paymentgateways,
imagegalleriesandmore.
BrowseWordPressPlugins
2014EnvatoPtyLtd.Trademarksandbrandsarethepropertyoftheirrespective
owners.
https://code.tutsplus.com/tutorials/ios8integratingtouchidcms21949 15/15