iOS
...
Users
User Log In
10 min
user log in and log out introduction in the user registration guide https //www back4app com/docs/ios/parse swift sdk/users/user registration we learned how to integrate a signup option into an ios app using the back4app platform and the parseswift sdk parseswift sdk once a user successfully signs up in your app, logging in and logging out actions are key features within the app’s flow the parseswift sdk parseswift sdk will allow us to integrate these features seamlessly into any ios app prerequisites to complete this quickstart, you need xcode an app created at back4app follow the new parse app tutorial to learn how to create a parse app at back4app note follow the install parse sdk (swift) tutorial to create an xcode project connected to back4app goal to implement a user login and logout feature using the parseswift sdk and the back4app platform 1 setting up the login and logout features before starting to implement any login functionality, we have to create the object that will represent the user for simplicity, we will reuse the same user user struct (which conforms to the parseuser parseuser protocol) we introduced in the user registration guide 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? } we recommend following the user registration guide and registering at least one user to use it as an example for this guide similar to the signup process, logging in requires a form where the user enters their username and password then, we perform a login request using the corresponding methods provided by the parseswift sdk parseswift sdk in its turn, back4app processes the request and returns a response containing the login information when an error occurs, the response returns information to identify and handle this error the logout process is straightforward the parseswift sdk parseswift sdk allows us to implement it in a single line of code 2 setting up the app once you connected https //www back4app com/docs/ios/parse swift sdk/install sdk your xcode project to your back4app application, the next step is to set up the app’s user interface for the login process, we will implement a simple controller containing the corresponding input fields and a login button the class in charge of this form is called logincontroller and it is a subclass of uiviewcontroller the key components to integrate into this controller are two uitextfield’s and one uibutton the following snippet shows the implementation of the logincontroller class 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 } additionally, the helper function showmessage(title\ message ) showmessage(title\ message ) is implemented in an extension of 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 } for the logout process, we insert a button in the home controller, i e , homecontroller homecontroller this view controller will only contain the logout button and a label showing the user’s username the implementation of this view controller is straightforward 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 request we now proceed to implement the login(with\ password) method in the logincontroller class the parseuser protocol gives the user object the static method login(username\ password) this method prepares and sends the login request to your back4app application depending on the use case, one can use one of the many implementations of the login( ) method we now complete the login(with\ password) method in 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 logout request the logout request is as simple as the login request once again, the parseuser protocol provides the user with the static method logout( ) by calling this method the current user (accessed via user current ) logs out from your back4app application we will call this method when the user taps the logout button located on the home screen, i e , in the handlelogout() method in the homecontroller class, we add the following 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 run the app! in this repository https //github com/templates back4app/ios user log in and log out , you will find an xcode project containing the login and logout processes we described above before running the app, make sure you connected the xcode project to your back4app back4app application conclusion the back4app and the parseswift sdk parseswift sdk allow us to integrate login and logout features in ios apps in a quick way after connecting your back4app application with your xcode project, the login (or logout) process only requires calling a single method