This guide describes the process of configuring your Backendless backend to enable the Google account sign-in in your application.

 

Adding Google+ API and generating client ID

1.Open https://console.developers.google.com in a browser.
2.Choose an existing project or create a new one.
newproject-google-signin
3.Select the Google+ API:
select-google-plus
4.Click Enable to enable the API:
click-to-enable
5.Once the API is enabled, click the Go to credentials button:
goto-credentials
6.Select iOS in the Where will you be calling the API from? drop-down list.
Also select User data in the What data will you be accessing? section as shown below:
ios-client-credentials
7.Click the What credentials do I need? button.

 

8.Enter your bundle ID, App Store ID and Team ID. Click the Create client ID button.
credentials-ios
9.Once the client ID is generated,the setup is complete. Click Done on the final screen.

 

Generating config file for client project

1.Navigate to https://developers.google.com/mobile/add
2.Click the Pick a platform button and make a platform (Android or iOS) selection.
3.Select the app from the dropdown, enter package name (Android) or bundle ID (iOS).
4.Click Choose and configure services.
5.Click Google Sign-in, then click Enable Google Sign-In.
6.Click Continue to Generate configuration files.
7.Click Download GoogleService-Info.plist.

 

Configuring Backend

1.Return to https://console.developers.google.com
2.Select the project and click Credentials.
3.The credentials should now include a "Web client" which is automatically generated by Google.
webclient
4.Click Web client.
5.Copy Client ID and Client secret into Google Plus ID and Google Plus Secret located in the Manage > App Settings > Social Settings in Backendless console:
client-id
 
social-settings
6.Click Save buttons in Backendless console.

 

Set up your CocoaPods dependencies

Google Sign-In uses CocoaPods to install and manage dependencies. Follow the instructions below to configure Google and Backendless pods:

1.Open a terminal window and navigate to the location of the Xcode project for your application. If you have not already created a Podfile for your application, create one now by running the following command:

pod init

2.Open the Podfile created for your application and add the following:
pod 'Google/SignIn'
pod 'Backendless'
3.Save the file and run the following command in the terminal window:

pod install

 
The result is a the .xcworkspace file created for your application. Use this file for continue the development of your application.

Add the configuration file to your project

Drag the GoogleService-Info.plist file created in the Generating config file for client project section into the root of your Xcode project and add it to all targets.

Add a URL scheme to your project

Google Sign-in requires a custom URL Scheme to be added to your project. To add the custom scheme:

1.Open your project configuration: double-click the project name in the left tree view. Select your app from the TARGETS section, then select the Info tab, and expand the URL Types section.
2.Click the + button, and add a URL scheme for your reversed client ID. To find this value, open the GoogleService-Info.plist configuration file, and look for the REVERSED_CLIENT_ID key. Copy the value of that key, and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.
google-services-plist
3.Click the + button, and add a URL scheme with Bundle Identifier. Leave the other fields blank.

 

When completed, your config should look something similar to the following (but with your application-specific values):

url-types

Add a Bridging-Header file into your Swift project

1.Add Bridging-Header.h file into the root of the project, and import the Google Sign-In SDK and Backendless SDK headers:
#import "Backendless.h"
#import <Google/SignIn.h>
2.Set "Bridging-Header.h" into the Build Settings "Objective-C Bridging Header" option:
bridging-header

Init Backendless app and Enable sign-in

To enable sign in, you must configure the GGLContext shared instance. You can do this in many places in your app. Often the best place to configure this instance is in your app delegate's application:didFinishLaunchingWithOptions: method.

 

Add into your AppDelegate class:

var backendless = Backendless.sharedInstance()
let APP_ID = "YOUR-APP-ID"
let SECRET_KEY = "YOUR_SECRET_KEY"
let VERSION_NUM = "v1"

func application(_ application: UIApplication, 
                   didFinishLaunchingWithOptions launchOptions: 
                               [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  backendless!.initApp(APP_ID, secret:SECRET_KEY, version:VERSION_NUM)
  // Initialize sign-in
  var configureError: NSError?
  GGLContext.sharedInstance().configureWithError(&configureError)
  assert(configureError == nil, "Error configuring Google services: \(configureError)")
  GIDSignIn.sharedInstance().delegate = self
  return true
}

Implement the application:openURL:options: method of your app delegate. The method should call the handleURL method of the GIDSignIn instance, which will properly handle the URL that your application receives at the end of the authentication process.

func application(_ app: UIApplication, 
                   open url: URL, 
                   options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
  // no equiv. notification. return NO if the application can't open for some reason
  let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String
  let annotation = options[UIApplicationOpenURLOptionsKey.annotation]
  print("AppDelegate (iOS9 >) -> application:openURL: \(url.scheme), 
                                 [\(sourceApplication) -> \(annotation)]")
  return GIDSignIn.sharedInstance().handle(url, 
                                           sourceApplication: sourceApplication, 
                                           annotation: annotation)
}

For your app to run on iOS 8 and older, also implement the deprecated application:openURL:sourceApplication:annotation: method:

@available(iOS, introduced: 4.2, 
                deprecated: 9.0, 
                message: "Please use application:openURL:options:")
func application(_ application: UIApplication, 
                    open url: URL, 
                    sourceApplication: String?, 
                    annotation: Any) -> Bool {
  print("AppDelegate (< iOS9) -> application:open url: \(url.scheme), 
        [\(sourceApplication) -> \(annotation)]")
  return GIDSignIn.sharedInstance().handle(url, 
                                           sourceApplication: sourceApplication, 
                                           annotation: annotation)
}

In your app delegate (AppDelegate.swift), declare class extension which implements the GIDSignInDelegate protocol to handle the sign-in process by defining the following methods:

extension AppDelegate : GIDSignInDelegate  {
  func sign(_ signIn: GIDSignIn!, 
              didSignInFor user: GIDGoogleUser!, 
              withError error: Error!) {
    if (error == nil) {
      // Perform backendless operations on signed in user here.
      let idToken = user.authentication.idToken
      let accessToken = user.authentication.accessToken
      print("idToken = '\(idToken)'")
      print("accessToken = '\(accessToken)'")
      let permissions = ["email"]
      let fieldsMapping = ["name": "name", "email": "email"]
      backendless!.userService.loginWithGoogleSign(
         inSDK: idToken, 
         accessToken: accessToken, 
         permissions: permissions, 
         fieldsMapping: fieldsMapping,
         response: {
            (user: BackendlessUser?) -> Void in
            print("user :\(user!.email) [\(user!.name)]")
         },
         error: {
           (fault: Fault?) -> Void in
           print("fault code :\(fault)")
         })
      }
    else {
      print("ERROR: \(error.localizedDescription)")
    }
  }
  
  @objc(signIn:didDisconnectWithUser:withError:) func sign(_ signIn: GIDSignIn!, 
                         didDisconnectWith user:GIDGoogleUser!, 
                         withError error: Error!) {
        print("User has disconnected.")
  }
}

 


Please let us know how we can improve the documentation by leaving a comment. All technical questions should be posted to the Backendless Support forum. We do not respond to the technical questions on the documentation pages.: