Platform
Mit Apple anmelden
15 min
anmeldung mit apple tutorial einführung die anmeldung mit apple ermöglicht es benutzern, sich mit ihrer apple id in apps anzumelden dieses feature ist verfügbar auf ios 13 und später sowie parse 3 5 und später voraussetzungen um dieses tutorial abzuschließen, benötigen sie eine app, die bei back4app erstellt wurde siehe tutorial zum erstellen einer neuen app um zu lernen, wie man eine app bei back4app erstellt richten sie eine subdomain für ihre back4app app ein siehe aktivierung ihres webhostings und live abfrage um zu lernen, wie man eine subdomain in back4app erstellt ein apple entwicklerkonto 1 erstellen sie eine neue back4app app zunächst ist es notwendig, sicherzustellen, dass sie eine vorhandene app bei back4app erstellt haben wenn sie jedoch ein neuer benutzer sind, können sie dieses tutorial https //www back4app com/docs/get started/new parse app lesen, um zu lernen, wie man eine erstellt 2 fügen sie die sign in mit apple funktionalität zu ihrem xcode projekt hinzu in ihrem xcode projekt klicken sie auf das target (1) und gehen sie zum tab signing & capabilities (2) klicken sie auf den + fähigkeit + fähigkeit button (3) und fügen sie die sign in mit apple sign in mit apple funktionalität (4) hinzu wählen sie dort ihre bundle identifier bundle identifier (5) aus und notieren sie diese information, da wir sie später benötigen 3 erstellen sie eine neue service id melden sie sich bei ihrem apple developer konto https //developer apple com/ an und gehen sie zum identifiers identifiers bereich überprüfen sie, ob ihr erstellter bundle identifier bundle identifier dort vorhanden ist klicken sie auf den bundle identifier bundle identifier und scrollen sie nach unten überprüfen sie, ob die sign in mit apple sign in mit apple option ausgewählt ist klicken sie bearbeiten bearbeiten und stellen sie sicher, dass die als primäre app id aktivieren als primäre app id aktivieren ausgewählt ist wenn alles richtig ist, speichern sie und beenden sie 4 richten sie parse auth für apple ein gehen sie zur back4app website, melden sie sich an und suchen sie ihre app klicken sie dann auf servereinstellungen servereinstellungen und suchen sie nach dem apple login apple login block und wählen sie einstellungen einstellungen der apple login apple login bereich sieht so aus jetzt müssen sie nur noch ihre bundle id bundle id in das feld unten einfügen und auf die schaltfläche klicken, um zu speichern falls sie probleme bei der integration von apple login haben, kontaktieren sie bitte unser team über den chat! 5 option 1 laden sie unsere vorlage herunter es sind einige programmierungen erforderlich, um die anmeldung mit apple zum laufen zu bringen, daher haben wir diese vorlage https //github com/templates back4app/parsesigninwithapple erstellt, die sie herunterladen und die bundle identifikator bundle identifikator , die app id app id , und client key client key ändern können der code ist vollständig dokumentiert, daher ist er ein guter ausgangspunkt wenn sie es vorziehen, dieses dokument durchzulesen, fahren sie bitte mit dem nächsten schritt fort 6 option 2 manuell code schreiben fügen sie in ihrer ansicht das authenticationservices framework hinzu und erstellen sie den authdelegate, der den pfuserauthenticationdelegate behandelt 1 import authenticationservices 2 3 class authdelegate\ nsobject, pfuserauthenticationdelegate { 4 func restoreauthentication(withauthdata authdata \[string string]?) > bool { 5 return true 6 } 7 8 func restoreauthenticationwithauthdata(authdata \[string string]?) > bool { 9 return true 10 } 11 } 7 implementieren sie ihre delegates für den viewcontroller implementieren sie das asauthorizationcontrollerdelegate und asauthorizationcontrollerpresentationcontextproviding für den viewcontroller 1 class viewcontroller uiviewcontroller, asauthorizationcontrollerdelegate, asauthorizationcontrollerpresentationcontextproviding 8 fügen sie die schaltfläche „mit apple anmelden“ hinzu die viewdidappear ist ein guter ort dafür wenn sie andere orte wählen, denken sie daran, es nur einmal aufzurufen 1 override func viewdidappear( animated bool) { 2 super viewdidappear(animated) 3 4 // sign in with apple button 5 let signinwithapplebutton = asauthorizationappleidbutton() 6 7 // set this so the button will use auto layout constraint 8 signinwithapplebutton translatesautoresizingmaskintoconstraints = false 9 10 // add the button to the view controller root view 11 self view\ addsubview(signinwithapplebutton) 12 13 // set constraint 14 nslayoutconstraint activate(\[ 15 signinwithapplebutton leadinganchor constraint(equalto view\ safearealayoutguide leadinganchor, constant 50 0), 16 signinwithapplebutton trailinganchor constraint(equalto view\ safearealayoutguide trailinganchor, constant 50 0), 17 signinwithapplebutton bottomanchor constraint(equalto view\ safearealayoutguide bottomanchor, constant 70 0), 18 signinwithapplebutton heightanchor constraint(equaltoconstant 50 0) 19 ]) 20 21 // the function that will be executed when user tap the button 22 signinwithapplebutton addtarget(self, action #selector(applesignintapped), for touchupinside) 23 } die applesignintapped in der letzten zeile muss ebenfalls innerhalb der viewcontroller klasse definiert werden 1 // this is the function that will be executed when user taps the button 2 @objc func applesignintapped() { 3 let provider = asauthorizationappleidprovider() 4 let request = provider createrequest() 5 // request full name and email from the user's apple id 6 request requestedscopes = \[ fullname, email] 7 8 // pass the request to the initializer of the controller 9 let authcontroller = asauthorizationcontroller(authorizationrequests \[request]) 10 11 // similar to delegate, this will ask the view controller 12 // which window to present the asauthorizationcontroller 13 authcontroller presentationcontextprovider = self 14 15 // delegate functions will be called when user data is 16 // successfully retrieved or error occured 17 authcontroller delegate = self 18 19 // show the sign in with apple dialog 20 authcontroller performrequests() 21 } 9 der presentationcontextprovider der presentationcontextprovider (asauthorizationcontrollerpresentationcontextproviding) wird fragen, welches fenster den autorisierungsdialog anzeigen soll da wir ihn im selben fenster anzeigen möchten, müssen wir self view\ window zurückgeben 1 func presentationanchor(for controller asauthorizationcontroller) > aspresentationanchor { 2 // return the current view window 3 return self view\ window! 4 } 10 umgang mit dem delegate asauthorizationcontrollerdelegate es gibt einige optionen, die wir behandeln müssen, wenn der delegate aufgerufen wird, also lassen sie uns etwas code hinzufügen, um diese optionen deutlich zu behandeln 1 func authorizationcontroller(controller asauthorizationcontroller, didcompletewitherror error error) { 2 print("authorization error") 3 guard let error = error as? asauthorizationerror else { 4 return 5 } 6 7 switch error code { 8 case canceled 9 // user press "cancel" during the login prompt 10 print("canceled") 11 case unknown 12 // user didn't login their apple id on the device 13 print("unknown") 14 case invalidresponse 15 // invalid response received from the login 16 print("invalid respone") 17 case nothandled 18 // authorization request not handled, maybe internet failure during login 19 print("not handled") 20 case failed 21 // authorization failed 22 print("failed") 23 @unknown default 24 print("default") 25 } 26 } 11 umgang mit dem delegate für didcompletewithauthorization wenn wir uns erfolgreich authentifizieren, können wir die autorisierten informationen abrufen 1 func authorizationcontroller(controller asauthorizationcontroller, didcompletewithauthorization authorization asauthorization) { 2 3 if let appleidcredential = authorization credential as? asauthorizationappleidcredential { 4 // unique id for each user, this uniqueid will always be returned 5 let userid = appleidcredential user 6 print("userid " + userid) 7 8 // if needed, save it to user defaults by uncommenting the line below 9 //userdefaults standard set(appleidcredential user, forkey "userid") 10 11 // optional, might be nil 12 let email = appleidcredential email 13 print("email " + (email ?? "no email") ) 14 15 // optional, might be nil 16 let givenname = appleidcredential fullname? givenname 17 print("given name " + (givenname ?? "no given name") ) 18 19 // optional, might be nil 20 let familyname = appleidcredential fullname? familyname 21 print("family name " + (familyname ?? "no family name") ) 22 23 // optional, might be nil 24 let nickname = appleidcredential fullname? nickname 25 print("nick name " + (nickname ?? "no nick name") ) 26 / 27 useful for server side, the app can send identitytoken and authorizationcode 28 to the server for verification purpose 29 / 30 var identitytoken string? 31 if let token = appleidcredential identitytoken { 32 identitytoken = string(bytes token, encoding utf8) 33 print("identity token " + (identitytoken ?? "no identity token")) 34 } 35 36 var authorizationcode string? 37 if let code = appleidcredential authorizationcode { 38 authorizationcode = string(bytes code, encoding utf8) 39 print("authorization code " + (authorizationcode ?? "no auth code") ) 40 } 41 42 // do what you want with the data here 43 44 } 45 } das ist der ort, an dem wir auch code für das einloggen in parse hinzufügen können direkt nach dem tun sie, was sie mit den daten hier wollen tun sie, was sie mit den daten hier wollen kommentar, fügen wir hinzu 1 pfuser loginwithauthtype(inbackground "apple", authdata \["token" string(identitytoken!), "id" userid]) continuewith { task > any? in 2 if ((task error) != nil){ 3 //dispatchqueue main async { 4 print("could not login \nplease try again ") 5 print("error with parse login after siwa \\(task error! localizeddescription)") 6 //} 7 return task 8 } 9 print("successfuly signed in with apple") 10 return nil 11 } und natürlich, fügen sie das parse framework hinzu 1 import parse