---
title: Sign In With Google
slug: docs/ios/parse-swift-sdk/users/sign-in-with-google
description: In this guide you wil learn how to log in a user using a Google account
image: https://www.back4app.com/images/logo-social.png
createdAt: 2024-03-11T16:37:11.023Z
---

# Sign In with Google

## Introduction

Nowadays, it is common for applications to offer more than one type of sign-in method. Therefore, for users it is easier to sign in with an account they already have, such as a Google account or Apple ID. Furthermore, social networks (like Facebook) make available an SDK for developers to integrate a sign-in option using their social network credentials.

We start this guide by first integrating the sign-in feature provided by Google. After the user successfully signed in with their Google credential, we use the account information returned by Google to sign in a new user that will be associated with the corresponding Google account.

In [this repository](https://github.com/templates-back4app/ios-sign-in-with-google), we provide a simple Xcode template where you can test the different sign-in methods we are implementing. This project was already introduced in the [previous guide](https://www.back4app.com/docs/ios/parse-swift-sdk/users/user-log-in), you can revisit it for more details about the project.

## Prerequisites

:::hint{type="info"}
**To complete this quickstart, you need:**

- Xcode.
- An app created at Back4App.
  - Follow the [New Parse App tutorial](https://www.back4app.com/docs/get-started/new-parse-app) to learn how to create a Parse app at **Back4App**.
  - **Note:&#x20;**&#x46;ollow the [Install Parse SDK (Swift) Tutorial](https://www.back4app.com/docs/ios/parse-swift-sdk) to create an Xcode Project connected to **Back4App**.
:::

## Goal

To integrate a user sign-in feature using Google’s SDK and **ParseSwift**.

## 1 - Setting up Google’s SDK

Once we have the Xcode project [linked](https://www.back4app.com/docs/ios/parse-swift-sdk/install-sdk) to the **Back4App** application, we proceed to add Google’s SDK which will allow us to implement the sign-in flow. For this example, we use the **Swift Package Manager** (SPM) to add Google Sign-in dependencies. In the Xcode project, go to **File>Add packages…** and in the search bar, look for **https\://github.com/google/GoogleSignIn-iOS**.

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/W3WNBnWdIwpab0RARKh7m_image.png)

Once the **GoogleSignIn-iOS** option appears in the results, click on the **Add Package** button.

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/yUrjEkpjPQ8W_QVk59c0G_image.png)

Next, go to the [dashboard](https://console.cloud.google.com/home/dashboard) of your Google developer account and [create](https://console.cloud.google.com/projectcreate) a new project.

Once the project has been created, the next step is to create an OAuth client id. In the [Google cloud console](https://console.cloud.google.com/) select your new project and go to the credentials page. This can be found from the left menu:

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/r3-nFClVX_I7MG_c_P31O_image.png)

During this process, you may need to set up the OAuth consent screen that will appear in the sign-in with Google form and fill in the corresponding requirements accordingly.

To conclude this step, we have to add in the app’s URL schemes the URL generated during the creation of the OAuth client id. Go to the project configuration and select the main app target. Then go to the **info** section and add the corresponding URL scheme from your Google project.

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/gaOoUD3YXw93XJ9If5Nu7_image.png)

## 2 - Using Google Sign in with ParseSwift

With **GoogleSignIn** successfully integrated into your Xcode project, we proceed to implement the sign in with Google feature. In the [project example](https://github.com/templates-back4app/ios-sign-in-with-google), the **LogInController** is in charge of handling and displaying the different sign-in options. We then set up the **signInWithAppleButton** action in this controller:

```swift
1   // LogInController.swift file
2   import GoogleSignIn
3   ...
4
5   class LogInController: UIViewController {
6     ...
7
8     private let signInWithGoogleButton: UIButton = {
9       let button = UIButton(type: .system)
10      button.setImage(UIImage(named: "googleIcon"), for: .normal)
11      button.imageView?.contentMode = .scaleAspectFit
12      return button
13    }()
14
15    override func viewDidLoad() {
16      super.viewDidLoad()
17      // ...
18      // Layout configuration
19      // ...
20
21      signInWithGoogleButton.addTarget(self, action: #selector(handleSignInWithGoogle), for: .touchUpInside)
22    }
23  }
24
25  // MARK: - Sign in with Google section
26  extension LogInController {
27    @objc fileprivate func handleSignInWithGoogle() {
28      // TODO: Here we will implement the sign-in procedure
29    }
30  }
```

In order to show the sign-in form from Google, the <font color="#2166ae">`GoogleSignIn`</font> SDK allows us to set up and present it via the <font color="#2166ae">`signIn(with:presenting:callback)`</font> method from the <font color="#2166ae">`GIDSignIn`</font> class. Additionally, we have to pass a <font color="#2166ae">`GIDConfiguration`</font> object instantiated using the **client id** created in the previous step, then presenting view controller, and a callback closure. In the callback closure, Google returns the user credentials (embedded in a <font color="#2166ae">`GIDGoogleUser`</font> object) or an error if the authentication failed.

```swift
1   // MARK: - Sign in with Google section
2   extension LogInController {
3     @objc fileprivate func handleSignInWithGoogle() {        
4       let signInConfig = GIDConfiguration(clientID: "MY_CLIENT_ID") // See https://developers.google.com/identity/sign-in/ios/sign-in for more details
5        
6       // Method provided by the GoogleSignIn framework. See https://developers.google.com/identity/sign-in/ios/sign-in for more details
7       GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { [weak self] googleUser, error in
8         if let error = error {
9           self?.showMessage(title: "Error", message: error.localizedDescription)
10          return
11        }
12            
13        // After Google returns a successful sign in, we get the users id and idToken
14        guard let googleUser = googleUser,
15              let userId = googleUser.userID,
16              let idToken = googleUser.authentication.idToken
17        else { fatalError("This should never happen!?") }
18            
19        // TODO: Sign in the user in your Back4App application.
20      }
21   }
22  }
```

We then take these credentials and use them to sign in to the user on the **Back4App** platform. The object representing the user is the following struct (see the [previous guide](https://www.back4app.com/docs/ios/parse-swift-sdk/users/user-log-in) for more details):&#x20;

```swift
1   import ParseSwift
2
3   struct User: ParseUser {
4     ...
5  
6     var username: String?
7     var email: String?
8     var emailVerified: Bool?
9     var password: String?
10  
11    var age: Int?
12  }
```

Therefore, the credential returned by Google contains an <font color="#2166ae">`idToken`</font> and the user’s <font color="#2166ae">`id`</font> that will be used to complete the sign-in process. More precisely, we instantiate a <font color="#2166ae">`ParseGoogle<User>`</font> object and call the <font color="#2166ae">`login(id:idToken:completion)`</font> method.

```swift
1   // MARK: - Sign in with Google section
2   extension LogInController {
3     @objc fileprivate func handleSignInWithGoogle() {
4       GIDSignIn.sharedInstance.signOut() // This should be called when the user logs out from your app. For login testing purposes, we are calling it each time the user taps on the 'signInWithGoogleButton' button.
5        
6       let signInConfig = GIDConfiguration(clientID: "MY_CLIENT_ID") // See https://developers.google.com/identity/sign-in/ios/sign-in for more details
7        
8       // Method provided by the GoogleSignIn framework. See https://developers.google.com/identity/sign-in/ios/sign-in for more details
9       GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { [weak self] googleUser, error in
10        if let error = error {
11          self?.showMessage(title: "Error", message: error.localizedDescription)
12          return
13        }
14            
15        // After Google returns a successful sign in, we get the users id and idToken
16        guard let googleUser = googleUser,
17              let userId = googleUser.userID,
18              let idToken = googleUser.authentication.idToken
19        else { fatalError("This should never happen!?") }
20            
21        // With the user information returned by Google, you need to sign in the user on your Back4App application
22        User.google.login(id: userId, idToken: idToken) { result in
23          // Returns the User object asociated to the GIDGoogleUser object returned by Google
24          switch result {
25            case .success(let user):
26            // After the login succeeded, we send the user to the home screen
27            // Additionally, you can complete the user information with the data provided by Google
28            let homeController = HomeController()
29            homeController.user = user
30
31            self?.navigationController?.pushViewController(homeController, animated: true)
32            case .failure(let error):
33            // Handle the error if the login process failed
34            self?.showMessage(title: "Failed to sign in", message: error.message)
35          }
36        }
37      }
38    }
39  }
```

## 3 - Verifying user sign in and session creation

To make sure, that the Google sign-in worked, you can look at your **Back4App** application dashboard and see the new <font color="#2166ae">`User`</font>, containing the Google <font color="#2166ae">`authData`</font> parameters.

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/CLeXCcDa0LxXyGQmBJZLY_image.png)

You can also verify that a valid session was created in the dashboard, containing a pointer to the corresponding <font color="#2166ae">`User`</font> object.

![](https://api.archbee.com/api/optimize/yD3zCY-NNBBIfd0uqcfR5/RxwT1HBT-eeK-RD3EkBlC_image.png)

## 4 - Linking an existing User to a Google account

In case your iOS App requires you to associate a Google account with an existing user in your **Back4App** platform, the <font color="#2166ae">`ParseGoogle<User>`</font> object implements the method <font color="#2166ae">`link(id:completion:)`</font> where you pass the <font color="#2166ae">`id`</font> of the Google account to be linked:

```swift
1   let googleUserId: String // The id of the Google account to link to
2
3   User.google.link(id: googleUserId) { [weak self] result in
4     switch result {
5     case .success(let user):
6       // Linking succeeded, user object now is linked to the corresponding Google account
7     case .failure(let error):
8       // Linking failed, handle the error
9     }
10  }
```

## 5 - Signing out

The sign-out process does not vary from the standard way of calling the <font color="#2166ae">`User.signout()`</font> method (detailed in previous guides). However, when a user signs in with a Google account, for consistency, you should sign out the current Google user as well. We can accomplish this by calling the following method alongside <font color="#2166ae">`User.signout()`</font>.

:::BlockQuote
**1   GIDSignIn.**&#x73;haredInstanc&#x65;**.signOut**()
:::

In order to verify if the current user has a linked Google account, you can check it by looking at the <font color="#2166ae">`User.current?.authData`</font> dictionary.

## 6 - Run the app

You can go to this [repository](https://github.com/templates-back4app/ios-sign-in-with-google) and download the example project. Before running the project, make sure you set up the provisioning profiles with the ones associated with your developer account.

## Conclusion

At the end of this guide, you learned how to sign in or link existing **Back4App** users on iOS using sign in with Google. In the next guide, we will continue with a different sign-in method.
