Platform
Apple로 가입하기
15 분
애플로 로그인 튜토리얼 소개 애플로 로그인을 사용하면 사용자가 애플 id를 사용하여 앱에 로그인할 수 있습니다 이 기능은 ios 13 및 이후 버전, parse 3 5 및 이후 버전에서 사용할 수 있습니다 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 back4app에서 생성된 앱 다음의 새 앱 만들기 튜토리얼 을 참조하여 back4app에서 앱을 만드는 방법을 알아보세요 back4app 앱을 위한 서브도메인 설정 다음의 웹 호스팅 및 실시간 쿼리 활성화 을 참조하여 back4app에서 서브도메인을 만드는 방법을 알아보세요 애플 개발자 계정 이 필요합니다 1 새로운 back4app 앱 만들기 우선, back4app에서 기존 앱이 생성되어 있는지 확인해야 합니다 그러나 새로운 사용자라면 이 튜토리얼 https //www back4app com/docs/get started/new parse app 을 확인하여 앱을 만드는 방법을 알아보세요 2 xcode 프로젝트에 apple로 로그인 기능 추가하기 xcode 프로젝트에서 target (1)을 클릭하고 signing & capabilities 탭 (2)으로 이동합니다 + 기능 + 기능 버튼 (3)을 클릭하고 apple로 로그인 apple로 로그인 기능 (4)을 추가합니다 그곳에서 번들 식별자 번들 식별자 (5)를 선택하고 나중에 필요할 정보를 기억해 두세요 3 새 서비스 id 만들기 당신의 apple 개발자 계정 https //developer apple com/ 에 로그인하고 식별자 식별자 섹션으로 이동합니다 생성한 번들 식별자 번들 식별자 가 있는지 확인합니다 번들 식별자 번들 식별자 를 클릭하고 아래로 스크롤합니다 apple로 로그인 apple로 로그인 이 선택되었는지 확인합니다 클릭 편집 편집 하고 기본 앱 id로 활성화 기본 앱 id로 활성화 가 선택되었는지 확인하세요 모든 것이 올바르다면, 저장하고 종료하세요 4 apple을 위한 parse auth 설정하기 back4app 웹사이트로 가서 로그인한 후, 앱을 찾으세요 그 후, 서버 설정 서버 설정 을 클릭하고 apple 로그인 apple 로그인 블록을 검색한 후, 설정 설정 을 선택하세요 apple 로그인 apple 로그인 섹션은 다음과 같습니다 이제 아래 필드에 bundle id bundle id 를 붙여넣고 저장 버튼을 클릭하면 됩니다 apple 로그인 통합 중 문제가 발생하면, 채팅을 통해 저희 팀에 문의해 주세요! 5 옵션 1 템플릿 다운로드 apple로 로그인하기 위해서는 약간의 코딩이 필요하므로, 이 템플릿 https //github com/templates back4app/parsesigninwithapple 을 만들었습니다 이 템플릿을 다운로드하여 bundle identifier bundle identifier , app id app id , 그리고 client key client key 을 변경할 수 있습니다 코드는 완전히 문서화되어 있으므로 좋은 출발점입니다 이 문서를 읽고 싶으시다면, 다음 단계로 진행해 주세요 6 옵션 2 수동으로 코드 작성하기 뷰 안에 authenticationservices 프레임워크를 추가하고 pfuserauthenticationdelegate를 처리할 authdelegate를 생성하세요 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 viewcontroller에 대한 delegates 구현하기 viewcontroller에 대해 asauthorizationcontrollerdelegate 및 asauthorizationcontrollerpresentationcontextproviding을 구현하세요 1 class viewcontroller uiviewcontroller, asauthorizationcontrollerdelegate, asauthorizationcontrollerpresentationcontextproviding 8 애플로 로그인 버튼 추가하기 viewdidappear는 그에 적합한 장소입니다 다른 장소를 선택할 경우, 한 번만 호출해야 한다는 것을 기억하세요 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 } 마지막 줄의 applesignintapped도 viewcontroller 클래스 안에 정의되어야 합니다 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 presentationcontextprovider presentationcontextprovider (asauthorizationcontrollerpresentationcontextproviding)는 어떤 창에서 인증 대화 상자를 표시할지를 요청합니다 우리는 같은 창에 표시할 것이므로 self view\ window를 반환해야 합니다 1 func presentationanchor(for controller asauthorizationcontroller) > aspresentationanchor { 2 // return the current view window 3 return self view\ window! 4 } 10 델리게이트 asauthorizationcontrollerdelegate 처리하기 델리게이트가 호출될 때 처리해야 할 몇 가지 옵션이 있으므로, 이러한 옵션을 구별하여 처리할 수 있도록 코드를 추가합시다 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 didcompletewithauthorization에 대한 델리게이트 처리하기 성공적으로 인증되면, 승인된 정보를 검색할 수 있습니다 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 } 여기가 parse에 로그인하는 코드를 추가할 수 있는 곳입니다 그래서 여기서 데이터로 원하는 작업을 수행하세요 여기서 데이터로 원하는 작업을 수행하세요 주석 바로 뒤에 추가해 보겠습니다 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 } 물론, parse 프레임워크를 추가하세요 1 import parse