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 你的 xcode 项目到你的 back4app 应用程序,下一步是设置应用程序的用户界面。 对于登录过程,我们将实现一个简单的控制器,其中包含相应的输入字段和一个登录按钮: 负责此表单的类称为 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 登录请求 我们现在开始在 logincontroller 类中实现 login(with\ password) 方法。 parseuser 协议为 user 对象提供了静态方法 login(username\ password) 。该方法准备并发送登录请求到您的 back4app 应用程序。根据使用情况,可以使用 login( ) 方法的多种实现之一。我们现在完成 login(with\ password) 方法在 logincontroller 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 项目连接后,登录(或登出)过程只需调用一个方法。