firebaseUI - google sign-in

27 篇文章 0 订阅

Authenticate Using Google Sign-In on iOS

You can let your users authenticate with Firebase using their Google Accounts by integrating Google Sign-In into your app.

Before you begin

  1. Add Firebase to your iOS project. Include the following pods in your Podfile:
     
       
    pod 'Firebase/Auth'
    pod
    'GoogleSignIn'
  2. If you haven't yet connected your app to your Firebase project, do so from the Firebase console.
  3. Enable Google Sign-In in the Firebase console:
    1. In the Firebase console, open the Auth section.
    2. On the Sign in method tab, enable the Google sign-in method and click Save.

1. Import the required header files

First, you must import the Firebase SDK and Google Sign-In SDK header files into your app.

SWIFT
OBJECTIVE-C

In your app delegate, import the following header files:

 
  
import Firebase
import GoogleSignIn

In the view controller of your sign-in view, import the following header files:

 
  
import Firebase
import GoogleSignIn

2. Implement Google Sign-In

Implement Google Sign-In by following these steps. See the Google Sign-In developer documentationfor details on using Google Sign-In with iOS.

  1. Add custom URL schemes to your Xcode project:
    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 Typessection.
    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 Schemesbox on the configuration page. Leave the other fields blank.

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

  2. Declare that the app delegate implements the GIDSignInDelegate protocol.
    SWIFT
    OBJECTIVE-C
    In  AppDelegate.swift:
     
        
    class AppDelegate : UIResponder , UIApplicationDelegate , GIDSignInDelegate {
  3. In your app delegate's application:didFinishLaunchingWithOptions: method, configure the FirebaseApp object and set the sign-in delegate.
    SWIFT
    OBJECTIVE-C
     
        
    // Use Firebase library to configure APIs
    FirebaseApp . configure ()

    GIDSignIn . sharedInstance (). clientID = FirebaseApp . app ()?. options . clientID
    GIDSignIn . sharedInstance (). delegate = self
  4. 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.
    SWIFT
    OBJECTIVE-C
     
        
    @available ( iOS 9.0 , *)
    func application
    ( _ application : UIApplication , open url : URL , options : [ UIApplicationOpenURLOptionsKey : Any ])
     
    -> Bool {
       
    return GIDSignIn . sharedInstance (). handle ( url ,
                                sourceApplication
    : options [ UIApplicationOpenURLOptionsKey . sourceApplication ] as ? String ,
                                annotation
    : [:])
    }

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

    SWIFT
    OBJECTIVE-C
     
        
    func application ( _ application : UIApplication , open url : URL , sourceApplication : String ?, annotation : Any ) -> Bool {
       
    return GIDSignIn . sharedInstance (). handle ( url ,
                                                 sourceApplication
    : sourceApplication ,
                                                 annotation
    : annotation )
    }
  5. In the app delegate, implement the GIDSignInDelegate protocol to handle the sign-in process by defining the following methods:
    OBJECTIVE-C
    SWIFT
     
        
    - ( void ) signIn :( GIDSignIn *) signIn
    didSignInForUser
    :( GIDGoogleUser *) user
         withError
    :( NSError *) error {
     
    // ...
     
    if ( error == nil ) {
       
    GIDAuthentication * authentication = user . authentication ;
       
    FIRAuthCredential * credential =
       
    [ FIRGoogleAuthProvider credentialWithIDToken : authentication . idToken
                                         accessToken
    : authentication . accessToken ];
       
    // ...
     
    } else {
       
    // ...
     
    }
    }

    - ( void ) signIn :( GIDSignIn *) signIn
    didDisconnectWithUser
    :( GIDGoogleUser *) user
         withError
    :( NSError *) error {
     
    // Perform any operations when the user disconnects from app here.
     
    // ...
    }
  6. Declare that your sign-in view's controller implements the GIDSignInUIDelegate protocol.
    SWIFT
    OBJECTIVE-C

    In the view controller:

     
        
    class MainViewController : UITableViewController , GIDSignInUIDelegate {
  7. In the view controller, override the viewDidLoad method to set the UI delegate of the GIDSignInobject, and (optionally) to sign in silently when possible.
    OBJECTIVE-C
    SWIFT
     
        
    - ( void ) viewDidLoad {
     
    [ super viewDidLoad ];

    [ GIDSignIn sharedInstance ]. uiDelegate = self ;
    [[ GIDSignIn sharedInstance ] signIn ];

     
    // TODO(developer) Configure the sign-in button look/feel
     
    // ...
    }
  8. Add a GIDSignInButton to your storyboard, XIB file, or instantiate it programmatically. To add the button to your storyboard or XIB file, add a View and set its custom class toGIDSignInButton.When you add a GIDSignInButton view to your storyboard, the sign-in button doesn't render in the interface builder. Run the app to see the sign-in button.
  9. Optional: If you want to customize the button, do the following:
    SWIFT
    OBJECTIVE-C
    1. In your view controller, declare the sign-in button as a property.
       
            
      @IBOutlet weak var signInButton: GIDSignInButton!
    2. Connect the button to the signInButton property you just declared.
    3. Customize the button by setting the properties of the GIDSignInButton object.

3. Authenticate with Firebase

In the signIn:didSignInForUser:withError: method, get a Google ID token and Google access token from the GIDAuthentication object and exchange them for a Firebase credential:

SWIFT
OBJECTIVE-C
 
  
func sign ( _ signIn : GIDSignIn !, didSignInFor user : GIDGoogleUser !, withError error : Error ?) {
 
// ...
 
if let error = error {
   
// ...
   
return
 
}

  guard let authentication
= user . authentication else { return }
  let credential
= GoogleAuthProvider . credential ( withIDToken : authentication . idToken ,
                                                    accessToken
: authentication . accessToken )
 
// ...
}

Finally, authenticate with Firebase using the credential:

SWIFT
OBJECTIVE-C
 
  
Auth . auth (). signIn ( with : credential ) { ( user , error ) in
 
if let error = error {
   
// ...
   
return
 
}
 
// User is signed in
 
// ...
}
}

Next steps

After a user signs in for the first time, a new user account is created and linked to the credentials—that is, the user name and password, phone number, or auth provider information—the user signed in with. This new account is stored as part of your Firebase project, and can be used to identify a user across every app in your project, regardless of how the user signs in.

  • In your apps, you can get the user's basic profile information from the FIRUser object. See Manage Users.

  • In your Firebase Realtime Database and Cloud Storage Security Rules, you can get the signed-in user's unique user ID from the auth variable, and use it to control what data a user can access.

You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account.

To sign out a user, call signOut:.

SWIFT
OBJECTIVE-C
 
  
    NSError * signOutError ;
BOOL status
= [[ FIRAuth auth ] signOut :& signOutError ];
if (! status ) {
 
NSLog (@ "Error signing out: %@" , signOutError );
 
return ;
}

You may also want to add error handling code for the full range of authentication errors. See Handle Errors.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值