iOS
...
Users
ParseSwift SDK로 iOS 애플리케이션 사용자 로그인 및 로그아웃 구현
10 분
사용자 로그인 및 로그아웃 소개 이 https //www back4app com/docs/ios/parse swift sdk/users/user registration 에서 우리는 back4app 플랫폼과 parseswift sdk parseswift sdk 를 사용하여 ios 앱에 가입 옵션을 통합하는 방법을 배웠습니다 사용자가 앱에서 성공적으로 가입하면 로그인 및 로그아웃 작업은 앱 흐름 내에서 핵심 기능입니다 이 parseswift sdk parseswift sdk 는 이러한 기능을 모든 ios 앱에 원활하게 통합할 수 있게 해줍니다 전제 조건 이 빠른 시작을 완료하려면 다음이 필요합니다 xcode back4app에서 생성된 앱 다음 https //www back4app com/docs/get started/new parse app 을 따라 back4app 에서 parse 앱을 만드는 방법을 배우세요 참고 다음 https //www back4app com/docs/ios/parse swift sdk 을 따라 back4app 에 연결된 xcode 프로젝트를 만드세요 목표 parseswift sdk와 back4app 플랫폼을 사용하여 사용자 로그인 및 로그아웃 기능을 구현하는 것입니다 1 로그인 및 로그아웃 기능 설정 로그인 기능을 구현하기 시작하기 전에, 사용자를 나타낼 객체를 생성해야 합니다 간단함을 위해, 우리는 다음과 같은 사용자 사용자 구조체를 재사용할 것입니다 (이는 parseuser parseuser 프로토콜을 준수합니다) 이는 https //www back4app com/docs/ios/parse swift sdk/users/user registration import foundation import parseswift struct user parseuser { var username string? var email string? var emailverified bool? var password string? var age int? } 사용자 등록 가이드를 따르고, 이 가이드의 예로 사용할 수 있도록 최소한 한 명의 사용자를 등록하는 것을 권장합니다 가입 프로세스와 유사하게, 로그인을 위해서는 사용자가 사용자 이름 과 비밀번호 을 입력하는 양식이 필요합니다 그런 다음, 우리는 parseswift sdk parseswift sdk 에서 제공하는 해당 메서드를 사용하여 로그인 요청을 수행합니다 그에 따라, back4app 은 요청을 처리하고 로그인 정보를 포함한 응답을 반환합니다 오류가 발생하면, 응답은 이 오류를 식별하고 처리하는 정보를 반환합니다 로그아웃 프로세스는 간단합니다 parseswift sdk parseswift sdk 는 이를 한 줄의 코드로 구현할 수 있게 해줍니다 2 앱 설정하기 당신이 https //www back4app com/docs/ios/parse swift sdk/install sdk 후, 다음 단계는 앱의 사용자 인터페이스를 설정하는 것입니다 로그인 프로세스를 위해, 우리는 해당 입력 필드와 로그인 버튼을 포함하는 간단한 컨트롤러를 구현할 것입니다 이 양식을 담당하는 클래스는 logincontroller라고 하며 uiviewcontroller의 서브클래스입니다 이 컨트롤러에 통합할 주요 구성 요소는 두 개의 uitextfield와 하나의 uibutton입니다 다음 코드 조각은 logincontroller 클래스의 구현을 보여줍니다 1 import uikit 2 import parseswift 3 4 class logincontroller uiviewcontroller { 5 private let usernametextfield uitextfield = { 6 let textfield = uitextfield() 7 textfield borderstyle = roundedrect 8 textfield placeholder = "username " 9 textfield autocapitalizationtype = none 10 textfield textalignment = center 11 return textfield 12 }() 13 14 private let passwordtextfield uitextfield = { 15 let textfield = uitextfield() 16 textfield borderstyle = roundedrect 17 textfield issecuretextentry = true 18 textfield placeholder = "password " 19 textfield textalignment = center 20 return textfield 21 }() 22 23 private let loginbutton uibutton = { 24 let button = uibutton(type roundedrect) 25 button settitle("log in", for normal) 26 return button 27 }() 28 29 override func viewdidload() { 30 super viewdidload() 31 32 navigationitem title = "back4app log in" 33 34 // lays out the login form 35 let stackview = uistackview(arrangedsubviews \[usernametextfield, passwordtextfield, loginbutton]) 36 stackview\ translatesautoresizingmaskintoconstraints = false 37 stackview\ spacing = 8 38 stackview\ axis = vertical 39 stackview\ distribution = fillequally 40 41 let stackviewheight = cgfloat(stackview\ arrangedsubviews count) (44 + stackview\ spacing) stackview\ spacing 42 43 view\ addsubview(stackview) 44 stackview\ centerxanchor constraint(equalto view\ safearealayoutguide centerxanchor) isactive = true 45 stackview\ centeryanchor constraint(equalto view\ safearealayoutguide centeryanchor) isactive = true 46 stackview\ widthanchor constraint(equalto view\ safearealayoutguide widthanchor, multiplier 0 7) isactive = true 47 stackview\ heightanchor constraint(equaltoconstant stackviewheight) isactive = true 48 49 // adds the method that will be called when the user taps the login button 50 loginbutton addtarget(self, action #selector(handlelogin), for touchupinside) 51 52 // if the user is already logged in, we redirect them to the homecontroller 53 guard let user = user current else { return } 54 let homecontroller = homecontroller() 55 homecontroller user = user 56 57 navigationcontroller? pushviewcontroller(homecontroller, animated true) 58 } 59 60 /// called when the user taps on the loginbutton button 61 @objc private func handlelogin() { 62 guard let username = usernametextfield text, !username isempty, 63 let password = passwordtextfield text, !password isempty else { 64 // shows an alert with the appropriate title and message 65 return showmessage(title "error", message "invalid credentials ") 66 } 67 68 login(with username, password password) 69 } 70 71 /// logs in the user and presents the app's home screen (homecontroller) 72 /// parameters 73 /// username user's username 74 /// password user's password 75 private func login(with username string, password string) { 76 // todo here we will implement the login process 77 } 78 } 또한, 헬퍼 함수 showmessage(title\ message ) showmessage(title\ message ) 는 uiviewcontroller uiviewcontroller 의 확장에서 구현됩니다 1 extension uiviewcontroller { 2 3 /// presents an alert with a title, a message and a back button 4 /// parameters 5 /// title title for the alert 6 /// message shor message for the alert 7 func showmessage(title string, message string) { 8 let alertcontroller = uialertcontroller(title title, message message, preferredstyle alert) 9 10 alertcontroller addaction(uialertaction(title "back", style cancel)) 11 12 present(alertcontroller, animated true) 13 } 14 } 로그아웃 프로세스를 위해 홈 컨트롤러에 버튼을 삽입합니다 즉, homecontroller homecontroller 이 뷰 컨트롤러는 로그아웃 버튼과 사용자의 사용자 이름을 표시하는 레이블만 포함합니다 이 뷰 컨트롤러의 구현은 간단합니다 1 import uikit 2 import parseswift 3 4 class homecontroller uiviewcontroller { 5 6 /// when set, it updates the usernamelabel's text with the user's username 7 var user user? { 8 didset { 9 usernamelabel text = "hello \\(user? username ?? "n/a")!" 10 } 11 } 12 13 private let usernamelabel uilabel = { 14 let label = uilabel() 15 label textalignment = center 16 label font = boldsystemfont(ofsize 18) 17 label translatesautoresizingmaskintoconstraints = false 18 return label 19 }() 20 21 private let logoutbutton uibutton = { 22 let button = uibutton(type roundedrect) 23 button settitle("log out", for normal) 24 button translatesautoresizingmaskintoconstraints = false 25 return button 26 }() 27 28 override func viewdidload() { 29 super viewdidload() 30 31 // sets up the layout (usernamelabel and logoutbutton) 32 view\ backgroundcolor = systembackground 33 navigationitem hidesbackbutton = true 34 navigationitem title = "back4app" 35 view\ addsubview(usernamelabel) 36 view\ addsubview(logoutbutton) 37 38 usernamelabel topanchor constraint(equalto view\ safearealayoutguide topanchor, constant 8) isactive = true 39 usernamelabel centerxanchor constraint(equalto view\ safearealayoutguide centerxanchor) isactive = true 40 41 logoutbutton bottomanchor constraint(equalto view\ safearealayoutguide bottomanchor, constant 8) isactive = true 42 logoutbutton centerxanchor constraint(equalto view\ safearealayoutguide centerxanchor) isactive = true 43 44 // adds the method that will be called when the user taps the logout button 45 logoutbutton addtarget(self, action #selector(handlelogout), for touchupinside) 46 } 47 48 /// called when the user taps the logout button 49 @objc private func handlelogout() { 50 // todo here we will implement the logout process 51 } 52 } 3 로그인 요청 이제 login(with\ password) 메서드를 logincontroller 클래스에 구현하겠습니다 parseuser 프로토콜은 user 객체에 정적 메서드 login(username\ password) 를 제공합니다 이 메서드는 로그인 요청을 back4app 애플리케이션으로 준비하고 전송합니다 사용 사례에 따라 login( ) 메서드의 여러 구현 중 하나를 사용할 수 있습니다 이제 logincontroller 에서 login(with\ password) 메서드를 완료하겠습니다 1 class homecontroller uiviewcontroller { 2 3 4 /// logs in the user and presents the app's home screen (homecontroller) 5 /// parameters 6 /// username user's username 7 /// password user's password 8 private func login(with username string, password string) { 9 // warning use only one of the following implementations, the synchronous or asynchronous option 10 11 // logs in the user synchronously, it throws a parseerror error if something happened 12 // this should be executed in a background thread! 13 do { 14 let loggedinuser = try user login(username username, password password) 15 16 // after the login success we send the user to the home screen 17 let homecontroller = homecontroller() 18 homecontroller user = loggedinuser 19 20 navigationcontroller? pushviewcontroller(homecontroller, animated true) 21 } catch let error as parseerror { 22 showmessage(title "error", message "failed to log in \\(error message)") 23 } catch { 24 showmessage(title "error", message "failed to log in \\(error localizeddescription)") 25 } 26 27 // logs in the user asynchronously 28 user login(username username, password password) { \[weak self] result in // handle the result (of type result\<user, parseerror>) 29 switch result { 30 case success(let loggedinuser) 31 self? usernametextfield text = nil 32 self? passwordtextfield text = nil 33 34 // after the login success we send the user to the home screen 35 let homecontroller = homecontroller() 36 homecontroller user = loggedinuser 37 38 self? navigationcontroller? pushviewcontroller(homecontroller, animated true) 39 case failure(let error) 40 self? showmessage(title "error", message "failed to log in \\(error message)") 41 } 42 } 43 } 44 } 4 로그아웃 요청 로그아웃 요청은 로그인 요청만큼 간단합니다 다시 말해, parseuser 프로토콜은 user 에게 정적 메서드 logout( ) 을 제공합니다 이 메서드를 호출하면 현재 사용자( user current )가 귀하의 back4app 애플리케이션에서 로그아웃됩니다 사용자가 홈 화면에 있는 로그아웃 버튼을 탭할 때 이 메서드를 호출할 것입니다 즉, handlelogout() 메서드에서 homecontroller 클래스에 다음을 추가합니다 1 class homecontroller uiviewcontroller { 2 3 4 /// called when the user taps the logout button 5 @objc private func handlelogout() { 6 // warning use only one of the following implementations, the synchronous or asynchronous option 7 8 // logs out the user synchronously, it throws a parseerror error if something happened 9 // this should be executed in a background thread! 10 do { 11 try user logout() 12 13 // after the logout succeeded we dismiss the home screen 14 navigationcontroller? popviewcontroller(animated true) 15 } catch let error as parseerror { 16 showmessage(title "error", message "failed to log out \\(error message)") 17 } catch { 18 showmessage(title "error", message "failed to log out \\(error localizeddescription)") 19 } 20 21 // logs out the user asynchronously 22 user logout { \[weak self] result in // handle the result (of type result\<void, parseerror>) 23 switch result { 24 case success 25 // after the logout succeeded we dismiss the home screen 26 self? navigationcontroller? popviewcontroller(animated true) 27 case failure(let error) 28 self? showmessage(title "error", message "failed to log out \\(error message)") 29 } 30 } 31 } 32 } 5 앱 실행하기! 이 https //github com/templates back4app/ios user log in and log out , 위에서 설명한 로그인 및 로그아웃 프로세스를 포함하는 xcode 프로젝트를 찾을 수 있습니다 앱을 실행하기 전에 xcode 프로젝트를 back4app back4app 애플리케이션에 연결했는지 확인하세요 결론 이 back4app 와 parseswift sdk parseswift sdk 는 ios 앱에서 로그인 및 로그아웃 기능을 빠르게 통합할 수 있게 해줍니다 back4app 애플리케이션을 xcode 프로젝트에 연결한 후, 로그인(또는 로그아웃) 프로세스는 단일 메서드를 호출하는 것만으로 충분합니다