iOS
...
Users
페이스북 계정으로 사용자 인증하기: Xcode 통합 가이드
16 분
페이스북으로 로그인 소개 이전 가이드에서, 사용자가 이전 가이드 https //www back4app com/docs/ios/parse swift sdk/users/sign in with google 를 통해 google 계정을 사용하여 back4app 애플리케이션에 로그인하는 방법을 배웠습니다 후속 조치로, 이제 facebook 계정을 대신 사용하는 로그인 대안을 추가할 수 있습니다 이를 위해 먼저 facebook의 개발자 페이지로 가서 xcode 프로젝트에 이러한 기능을 통합하기 위한 요구 사항을 설정합니다 facebook은 개발자에게 다양한 앱 중에서 페이스북으로 로그인 옵션을 통합할 수 있는 sdk를 제공합니다 이 저장소 에서는 구현 중인 다양한 로그인 방법을 테스트할 수 있는 간단한 xcode 템플릿을 제공합니다 이 예제는 이미 로그인 가이드 https //www back4app com/docs/ios/parse swift sdk/users/user log in 에서 소개되었습니다 프로젝트에 대한 자세한 내용은 다시 방문할 수 있습니다 전제 조건 이 빠른 시작을 완료하려면 다음이 필요합니다 최신 버전의 xcode back4app에서 생성된 앱 다음 새 parse 앱 튜토리얼 을 따라 back4app 에서 parse 앱을 만드는 방법을 배우세요 참고 다음 parse sdk (swift) 설치 튜토리얼 을 따라 back4app 에 연결된 xcode 프로젝트를 만드세요 목표 사용자 로그인 기능을 facebook의 sdk와 parseswift 를 사용하여 통합합니다 1 facebook의 sdk 설정하기 xcode 프로젝트가 연결된 back4app 애플리케이션에 추가된 후, 로그인 흐름을 구현할 수 있도록 facebook의 sdk를 추가합니다 이 예제에서는 swift package manager (spm)을 사용하여 facebook 로그인 종속성을 추가합니다 xcode 프로젝트에서 파일>패키지 추가… 로 가서 검색창에 https //github com/facebook/facebook ios sdk https //github com/facebook/facebook ios sdk 를 찾습니다 결과에 facebook ios sdk 가 나타나면 패키지 추가 버튼을 클릭합니다 다음으로, 앱 섹션으로 이동하여 새 앱을 만드세요 앱의 유형을 입력하고 다음 페이지로 이동하세요 나머지 정보를 입력하고 앱 만들기 를 클릭하세요 앱 페이지에 있는 새로 만든 앱을 찾아서 앱 id 를 복사하고 이름을 클릭하여 대시보드로 들어가세요 오른쪽 상단에는 facebook 개발자 계정과 연결된 클라이언트 id 가 있습니다 이 두 id는 다음 구성에 필요합니다 facebook이 로그인 기능을 설정하기 위해 필요한 다음 구성은 xcode info plist 파일에 몇 가지 키 값 데이터를 입력하는 것입니다 더 정확하게는, xcode 프로젝트 탐색기로 이동하여 info plist를 찾아 소스 코드 로 엽니다 다음 값을 추가하세요 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 "app id" 문자열을 새로 생성된 앱과 연결된 "app id"로 교체하십시오 "client token" 문자열은 "대시보드>설정>고급>보안>클라이언트 토큰"에 위치한 클라이언트 토큰으로 교체해야 합니다 이제 xcode 프로젝트에 "keychain sharing" 기능을 추가해야 합니다 이를 위해 프로젝트 탐색기에서 프로젝트를 선택하고 타겟 섹션으로 이동합니다 타겟을 선택하고 "서명 및 기능" 탭으로 이동한 다음, "+ 기능" 버튼을 클릭하고 "keychain sharing" 기능을 추가하십시오 다음과 같이 appdelegate , application( didfinishlaunchingwithoptions ) 델리게이트 메서드에 다음 줄을 추가합니다 (먼저 facebookcore 프레임워크를 가져오는 것을 잊지 마세요) 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 } 마지막으로, scenedelegate , 들어오는 url 컨텍스트를 처리하기 위해 다음 코드를 추가합니다 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 parseswift와 함께 facebook 로그인 사용하기 facebooklogin이 xcode 프로젝트에 성공적으로 통합되었으므로, facebook으로 로그인 기능을 구현합니다 프로젝트 예제 , logincontroller는 다양한 로그인 옵션을 처리하고 표시하는 역할을 합니다 그런 다음 signinwithfacebookbutton 액션을 설정합니다 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 } facebook에서 로그인 양식을 표시하기 위해 facebooklogin sdk를 사용하여 signin(with\ presenting\ callback) 메서드를 통해 설정하고 표시할 수 있습니다 loginmanager 클래스에서 우리는 facebook에서 수집하고자 하는 데이터와 관련된 string 값이 포함된 배열을 전달해야 합니다 일반적인 값은 public profile 및 email 입니다 반면에 두 번째 매개변수는 facebook이 사용자 자격 증명( loginmanagerloginresult 객체에 포함됨) 또는 인증 실패 시 오류를 반환하는 콜백 클로저입니다 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 } 그런 다음 이 자격 증명을 사용하여 사용자가 back4app 플랫폼에 로그인하도록 합니다 사용자를 나타내는 객체는 다음 구조체입니다 (자세한 내용은 로그인 가이드 https //www back4app com/docs/ios/parse swift sdk/users/user log in 를 참조하세요) 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 } 따라서 facebook에서 반환된 자격 증명에는 액세스 토큰과 사용자 id가 포함되어 있으며, 이는 로그인 프로세스를 완료하는 데 사용됩니다 더 정확하게는, parsefacebook\<user> 객체를 인스턴스화하고 login(userid\ authenticationtoken\ completion ) 메서드를 호출합니다 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 사용자 로그인 확인 및 세션 생성 google 로그인이 작동했는지 확인하려면, back4app 애플리케이션 대시보드를 확인하고 facebook authdata 매개변수를 포함하는 새로운 사용자를 확인할 수 있습니다 대시보드에서 유효한 세션이 생성되었는지 확인할 수 있으며, 해당 사용자 객체에 대한 포인터가 포함되어 있습니다 4 기존 사용자와 facebook 계정 연결하기 ios 앱이 back4app 플랫폼의 기존 사용자와 facebook 계정을 연결해야 하는 경우, parsefacebook\<user> 객체는 link(id\ accesstoken\ completion ) 메서드를 구현합니다 여기서 facebook 계정의 userid 와 세션과 관련된 accesstoken 을 전달합니다 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 로그아웃 로그아웃 과정은 user signout() 메서드를 호출하는 표준 방법과 다르지 않습니다(이전 가이드에서 자세히 설명됨) 그러나 사용자가 facebook 계정으로 로그인한 경우, 일관성을 위해 현재 facebook 사용자도 로그아웃해야 합니다 이를 위해 user signout()와 함께 다음 메서드를 호출할 수 있습니다 현재 사용자가 연결된 facebook 계정이 있는지 확인하려면 user current? authdata 사전을 확인하면 됩니다 6 앱 실행하기 이 저장소 로 가서 예제 프로젝트를 다운로드할 수 있습니다 프로젝트를 실행하기 전에 개발자 계정과 연결된 프로비저닝 프로필을 설정했는지 확인하세요 결론 이 가이드의 끝에서, facebook으로 로그인하거나 기존 back4app 사용자를 ios에서 연결하는 방법을 배웠습니다 다음 가이드에서는 다른 로그인 방법에 대해 계속 진행할 것입니다