iOS
...
Users
Sign In with Facebook
16 min
sign in with facebook introduction in the https //www back4app com/docs/ios/parse swift sdk/users/sign in with google , we learned how a user signs into a back4app application using a google account as a follow up, we may now add a sign in alternative that uses a facebook account instead to accomplish this, we first go to facebook’s developer page and set up the requirements to integrate such functionality in an xcode project facebook provides an sdk to developers to integrate a sign in with facebook option among different apps in https //github com/templates back4app/ios sign in with facebook , we provide a simple xcode template where you can test the different sign in methods we are implementing this example was already introduced in the https //www back4app com/docs/ios/parse swift sdk/users/user log in , you can revisit it for more details about the project prerequisites to complete this quickstart, you need a recent version of xcode an app created at back4app follow the https //www back4app com/docs/get started/new parse app to learn how to create a parse app at back4app note follow the https //www back4app com/docs/ios/parse swift sdk to create an xcode project connected to back4app goal to integrate a user sign in feature using facebook’s sdk and parseswift 1 setting up facebook’s sdk once we have the xcode project https //www back4app com/docs/ios/parse swift sdk/install sdk to the back4app application, we proceed to add facebook’s sdk which will allow us to implement the sign in flow for this example, we use the swift package manager (spm) to add facebook login dependencies in the xcode project, go to file>add packages… and in the search bar, look for https //github com/facebook/facebook ios sdk once the facebook ios sdk appears in the results, click on the add package button next, go to the https //developers facebook com/apps/ section of your facebook developer account and create a new app enter the type of app your app belongs to and go to the next page enter the remaining information and click on create app while you are on your https //developers facebook com/apps/ page, locate your newly created app, copy its app id and enter the dashboard by clicking on its name in the top right, it is located the client id associated with your facebook developer account these two ids are necessary for the following configuration the next configuration facebook needs to set up the sign in capability is to enter a couple of key value data in your xcode info plist file more precisely, go to your xcode project navigator, locate the info plist and open it as source code add the following values 1 cfbundleurltypes 2 3 4 cfbundletyperole 5 editor 6 cfbundleurlschemes 7 	 8 fbapp id 9 10 11 12 facebookappid 13 app id 14 facebookclienttoken 15 client token 16 lsapplicationqueriesschemes 17 18 fbapi 19 fb messenger share api 20 replace the app id string with the app id associated with the newly created app on facebook the client token string has to be replaced with the client token located in dashboard>settings>advanced>security>client token now we have to add the keychain sharing capability to the xcode project to do this, select your project from the project navigator and go to the targets section select a target and go to the signing & capabilities tab, then click on the + capability button and add the keychain sharing capability in the appdelegate , we add the following line in the application( didfinishlaunchingwithoptions ) delegate method (make sure you import the facebookcore framework first) 1 import facebookcore 2 3 @main 4 class appdelegate uiresponder, uiapplicationdelegate { 5 func application( application uiapplication, didfinishlaunchingwithoptions launchoptions \[uiapplication launchoptionskey any]?) > bool { 6 7 8 applicationdelegate shared application(application, didfinishlaunchingwithoptions launchoptions) 9 return true 10 } 11 12 13 } lastly, in the scenedelegate , we add the following code to handle incoming url contexts 1 import facebookcore 2 3 class scenedelegate uiresponder, uiwindowscenedelegate { 4 5 6 func scene( scene uiscene, openurlcontexts urlcontexts set\<uiopenurlcontext>) { 7 guard let url = urlcontexts first? url else { 8 return 9 } 10 11 applicationdelegate shared application( 12 uiapplication shared, 13 open url, 14 sourceapplication nil, 15 annotation \[uiapplication openurloptionskey annotation] 16 ) 17 } 18 } 2 using facebook login with parseswift with facebooklogin successfully integrated into your xcode project, we proceed to implement the sign in with facebook feature in the https //github com/templates back4app/ios sign in with facebook , the logincontroller is in charge of handling and displaying the different sign in options we then set up the signinwithfacebookbutton action 1 // logincontroller swift file 2 import facebooklogin 3 4 5 class logincontroller uiviewcontroller { 6 7 8 private let signinwithfacebookbutton uibutton = { 9 let button = uibutton(type system) 10 button setimage(uiimage(named "facebookicon"), for normal) 11 button imageview? contentmode = scaleaspectfit 12 return button 13 }() 14 15 override func viewdidload() { 16 super viewdidload() 17 // 18 // layout configuration 19 // 20 21 signinwithfacebookbutton addtarget(self, action #selector(handlesigninwithfacebook), for touchupinside) 22 } 23 } 24 25 // mark sign in with facebook section 26 extension logincontroller { 27 @objc fileprivate func handlesigninwithfacebook() { 28 // todo here we will implement the sign in procedure 29 } 30 } in order to show the sign in form from facebook, the facebooklogin sdk allows us to set up and present it via the signin(with\ presenting\ callback) method from the loginmanager class we have to pass an array containing string values associated with the data we want to gather from facebook the common values are public profile and email on the other hand, the second parameter is a callback closure where facebook returns the user credential (embedded in a loginmanagerloginresult object) or an error if the authentication fails 1 // mark sign in with facebook section 2 extension logincontroller { 3 @objc fileprivate func handlesigninwithfacebook() { 4 let loginmanager = loginmanager() 5 6 // method provided by the facebook sdk see https //developers facebook com/docs/facebook login/ios/ for more details 7 loginmanager login(permissions \["public profile", "email"], from self) { \[weak self] result, error in 8 if let error = error { 9 self? showmessage(title "error", message error localizeddescription) 10 return 11 } else if let result = result, result iscancelled { 12 self? showmessage(title "alert", message "sign in cancelled") 13 return 14 } 15 16 // once facebook successfully signs in the user, we retrieve the information related to the sign in process via the result token object, an accesstoken class type 17 guard let accesstoken = result? token else { fatalerror("this dhould never hapen ") } 18 19 // todo sign in the user on your back4app application with the accesstoken 20 } 21 } 22 } we then take this credential and use them for the user to sign in to the back4app platform the object representing the user is the following struct (see the https //www back4app com/docs/ios/parse swift sdk/users/user log in for more details) 1 import parseswift 2 3 struct user parseuser { 4 5 6 var username string? 7 var email string? 8 var emailverified bool? 9 var password string? 10 11 var age int? 12 } therefore, the credential returned by facebook contains an accesstoken and the user’s id that will be used to complete the sign in process more precisely, we instantiate a parsefacebook\<user> object and call the login(userid\ authenticationtoken\ completion ) method 1 // mark sign in with facebook section 2 extension logincontroller { 3 @objc fileprivate func handlesigninwithfacebook() { 4 let loginmanager = loginmanager() 5 6 // method provided by the facebook sdk see https //developers facebook com/docs/facebook login/ios/ for more details 7 loginmanager login(permissions \["public profile", "email"], from self) { \[weak self] result, error in 8 if let error = error { 9 self? showmessage(title "error", message error localizeddescription) 10 return 11 } else if let result = result, result iscancelled { 12 self? showmessage(title "alert", message "sign in cancelled") 13 return 14 } 15 16 // once facebook successfully signed in the user, we retrieve the information related to the sign in process via the result token object, an accesstoken class type 17 guard let accesstoken = result? token else { fatalerror("this dhould never hapen ") } 18 19 // with the accesstoken returned by facebook, you need to sign in the user on your back4app application 20 user facebook login(userid accesstoken userid, accesstoken accesstoken tokenstring) { \[weak self] result in 21 // returns the user object asociated to the facebook user returned by facebook 22 switch result { 23 case success(let user) 24 // after the login succeeded, we send the user to the home screen 25 // additionally, you can complete the user information with the data provided by facebook 26 let homecontroller = homecontroller() 27 homecontroller user = user 28 29 self? navigationcontroller? pushviewcontroller(homecontroller, animated true) 30 case failure(let error) 31 // handle the error if the login process failed 32 self? showmessage(title "failed to sign in", message error message) 33 } 34 } 35 } 36 } 37 } 3 verifying user sign in and session creation to make sure that the google sign in worked, you can look at your back4app application dashboard and see the new user containing the facebook authdata parameters you can also verify that a valid session was created in the dashboard, containing a pointer to the corresponding user object 4 linking an existing user to a facebook account in case your ios app requires you to associate a facebook account to an existing user in your back4app platform, the parsefacebook\<user> object implements the method link(id\ accesstoken\ completion ) where you pass the userid of the facebook account and the accesstoken associated with the session 1 let facebookuserid string // the userid of the facebook account to link to 2 let accesstoken string = accesstoken current! tokenstring // the access token of the currently signed in facebook user 3 4 user facebook link(userid facebookuserid, accesstoken accesstoken) { result in 5 switch result { 6 case success(let user) 7 // linking succeeded, the user is now linked to the corresponding facebook account 8 case failure(let error) 9 // linking failed, handle the error 10 } 11 } 5 signing out the sign out process does not vary from the standard way of calling the user signout() method (detailed in previous guides) however, when a user signs in with a facebook account, for consistency, you have to sign out the current facebook user as well we can accomplish this by calling the following method alongside user signout() 1 loginmanager () logout () in order to verify if the current user has a linked facebook account, you can check it by looking at the user current? authdata dictionary 6 run the app you can go to this https //github com/templates back4app/ios sign in with facebook and download the example project before running the project, make sure you set up the provisioning profiles with the ones associated with your developer account conclusion at the end of this guide, you learned how to sign in or link existing back4app users on ios using sign in with facebook in the next guide, we will continue with a different sign in method