Learn how to build a screen where you can sign in with Google on iOS, in Swift language.
Create OAuth Credentials
Sign in to your Google Cloud Console and click the + CREATE CREDENTIALS button. Select the OAuth Client ID option.
On the next page:
- Select the iOS Application type
- Give a name to your OAuth client
- Paste the Bundle Identifier of your app - the one in the General tab in Xcode
- Click the CREATE button
You will get a pop with the just created OAuth client ID
. Ignore it, close the popup and click on your OAuth client's row to enter its details.
Keep this page open and switch to Xcode.
Configure the Xcode project
Assuming you already have created a new Xcode project, a Database on xserver.app, and included the XServer's SDK files in your project - as explained in this section of the Documentation - you have to create a ViewController in the Storyboard with a button that will allow users to sign in with Google.
Something like this:
Connect that button to your .swift
file and call its IBAction as googleButton
.
Download the Google Sign In framework here and drag these 3 files inside your project - in the left panel which hosts the list of files:
Now enter the XServerSDK.swift
file and add this variable right below the imports:
let GOOGLE_SIGN_IN_CLIENT_ID = ""
Go back to your Google Cloud Console page, copy the Client ID and paste it between the ""
of the above variable:
let GOOGLE_SIGN_IN_CLIENT_ID = "191234567890-iparcjjt2reg3kqsri85vgk.apps.googleusercontent.com"
Lastly:
- Copy the iOS URL scheme string form your Google Cloud Console
- Open the Info tab in Xcode.
- Expand the URL Types section.
- Paste the copied URL scheme into the URL schemes field.
Make it happen
Now, let's code!
In your .swift
file, start by importing these frameworks:
import AuthenticationServices
import GoogleSignIn
Add the GIDSignInDelegate
to your class declaration:
class ViewController: UIViewController, GIDSignInDelegate { ... }
Right below it, declare the following variable:
var googleSignIn = GIDSignIn.sharedInstance()
Inside the googleButton()
IBAction function, paste this code:
googleSignIn?.presentingViewController = self
googleSignIn?.clientID = GOOGLE_SIGN_IN_CLIENT_ID
googleSignIn?.delegate = self
googleSignIn?.signIn()
Use this function to make the magic and lat users sign in with Google:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
guard let user = user else {
print("Google login cancelled.")
return
}
// Get user's data
let password = user.userID ?? ""
// let authToken = user.authentication.idToken ?? ""
let firstName = user.profile.givenName ?? ""
let lastName = user.profile.familyName ?? ""
let email = user.profile.email ?? password + "@google.com"
let profilePicURL = user.profile.imageURL(withDimension: 150)?.absoluteString ?? DATABASE_PATH + "assets/img/default_avatar.png" // If the Google user doesn't have a profile photo, the XServer's default one will be used
let username = firstName.lowercased() + lastName.lowercased()
// Call the Sign Up function from the XServer SDK
self.XSSignUp(username: username, password: password, email: email, signInWith: "google") { (results, e) in
if error == nil {
let resultsArr = results!.components(separatedBy: "-")
let uID = resultsArr[0]
let isSignInWithAppleGoogle = resultsArr[1]
// Go back
if isSignInWithAppleGoogle == "true" {
print("User previously signed up, so now it's signed back in!")
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
// Add additional data
let params = [
self.param(columnName: "tableName", value: "Users"),
self.param(columnName: "ID_id", value: uID),
self.param(columnName: "FL_profilePic", value: profilePicURL),
]
self.XSObject(params) { (e, obj) in
if e == nil {
print("Google user just signed up!")
// error
} else { DispatchQueue.main.async { print(e!)
}}}// ./ XSObject
})
} // ./ If
} else { DispatchQueue.main.async { print(e!) }
}}// ./ XSSignUp()
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
// Call your backend server to delete user's info after they requested to delete their account
}
Remember to create a Column of type File and name it as
profilePic
in your database, so the SDK will store the Google profile photo in your database after launching the app with the above code!
Done, now you and other users can sign up or sign in to your app with their Google account.
If you want more info about the XServer backend, just visit the official website and read the Documentation.