Google 致力于为黑人社区推动种族平等。查看具体举措

在 Apple 平台上使用 Google 登录进行身份验证

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

您可以通过将 Google Sign-In 集成到您的应用中,让您的用户使用他们的 Google 帐户向 Firebase 进行身份验证。

在你开始之前

  1. 将 Firebase 添加到您的 Apple 项目中。在您的Podfile中包含以下 pod:
    pod 'FirebaseAuth'
    pod 'GoogleSignIn'
    
  2. 如果您尚未将应用连接到 Firebase 项目,请从Firebase 控制台执行此操作。
  3. 在 Firebase 控制台中启用 Google 作为登录方法:
    1. Firebase 控制台中,打开Auth部分。
    2. 登录方法选项卡上,启用Google登录方法并单击保存

1.导入需要的头文件

首先,您必须将 Firebase SDK 和 Google Sign-In SDK 头文件导入您的应用。

迅速

import FirebaseCore
import GoogleSignIn

Objective-C

@import FirebaseCore;
@import GoogleSignIn;

2. 实施谷歌登录

按照以下步骤实施 Google 登录。有关在 iOS 中使用 Google Sign-In 的详细信息,请参阅Google Sign-In 开发人员文档

  1. 将自定义 URL 方案添加到您的 Xcode 项目:
    1. 打开您的项目配置:双击左侧树视图中的项目名称。从TARGETS部分中选择您的应用程序,然后选择Info选项卡,然后展开URL Types部分。
    2. 单击+按钮,并为您的反向客户端 ID 添加 URL 方案。要查找此值,请打开GoogleService-Info.plist配置文件,然后查找REVERSED_CLIENT_ID键。复制该键的值,并将其粘贴到配置页面上的URL 方案框中。将其他字段留空。

      完成后,您的配置应类似于以下内容(但使用特定于应用程序的值):

  2. 在您的应用委托的application:didFinishLaunchingWithOptions:方法中,配置FirebaseApp对象。

    迅速

    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
    
  3. 实现应用程序委托的application:openURL:options:方法。该方法应调用GIDSignIn实例的handleURL方法,该方法将正确处理您的应用程序在身份验证过程结束时收到的 URL。

    迅速

    @available(iOS 9.0, *)
    func application(_ application: UIApplication, open url: URL,
                     options: [UIApplication.OpenURLOptionsKey: Any])
      -> Bool {
      return GIDSignIn.sharedInstance.handle(url)
    }
    

    Objective-C

    - (BOOL)application:(nonnull UIApplication *)application
                openURL:(nonnull NSURL *)url
                options:(nonnull NSDictionary<NSString *, id> *)options {
      return [[GIDSignIn sharedInstance] handleURL:url];
    }
    
  4. 将应用的呈现视图控制器和客户端 ID 传递给 Google Sign In 登录方法,并从生成的 Google 身份验证令牌创建 Firebase 身份验证凭据:

    迅速

    guard let clientID = FirebaseApp.app()?.options.clientID else { return }
    
    // Create Google Sign In configuration object.
    let config = GIDConfiguration(clientID: clientID)
    
    // Start the sign in flow!
    GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in
    
      if let error = error {
        // ...
        return
      }
    
      guard
        let authentication = user?.authentication,
        let idToken = authentication.idToken
      else {
        return
      }
    
      let credential = GoogleAuthProvider.credential(withIDToken: idToken,
                                                     accessToken: authentication.accessToken)
    
      // ...
    }
    

    Objective-C

    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID];
    
    __weak __auto_type weakSelf = self;
    [GIDSignIn.sharedInstance signInWithConfiguration:config presentingViewController:self callback:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
      __auto_type strongSelf = weakSelf;
      if (strongSelf == nil) { return; }
    
      if (error == nil) {
        GIDAuthentication *authentication = user.authentication;
        FIRAuthCredential *credential =
        [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken
                                         accessToken:authentication.accessToken];
        // ...
      } else {
        // ...
      }
    }];
    
    
  5. GIDSignInButton添加到您的故事板、XIB 文件,或以编程方式对其进行实例化。要将按钮添加到情节提要或 XIB 文件,请添加一个 View 并将其自定义类设置为GIDSignInButton
  6. 可选:如果要自定义按钮,请执行以下操作:

    迅速

    1. 在您的视图控制器中,将登录按钮声明为属性。
      @IBOutlet weak var signInButton: GIDSignInButton!
    2. 将按钮连接到您刚刚声明的signInButton属性。
    3. 通过设置GIDSignInButton对象的属性来自定义按钮。

    Objective-C

    1. 在视图控制器的头文件中,将登录按钮声明为属性。
      @property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
    2. 将按钮连接到您刚刚声明的signInButton属性。
    3. 通过设置GIDSignInButton对象的属性来自定义按钮。

3. 使用 Firebase 进行身份验证

最后,使用上一步中创建的身份验证凭据完成 Firebase 登录过程。

迅速

Auth.auth().signIn(with: credential) { authResult, error in
    if let error = error {
      let authError = error as NSError
      if isMFAEnabled, authError.code == AuthErrorCode.secondFactorRequired.rawValue {
        // The user is a multi-factor user. Second factor challenge is required.
        let resolver = authError
          .userInfo[AuthErrorUserInfoMultiFactorResolverKey] as! MultiFactorResolver
        var displayNameString = ""
        for tmpFactorInfo in resolver.hints {
          displayNameString += tmpFactorInfo.displayName ?? ""
          displayNameString += " "
        }
        self.showTextInputPrompt(
          withMessage: "Select factor to sign in\n\(displayNameString)",
          completionBlock: { userPressedOK, displayName in
            var selectedHint: PhoneMultiFactorInfo?
            for tmpFactorInfo in resolver.hints {
              if displayName == tmpFactorInfo.displayName {
                selectedHint = tmpFactorInfo as? PhoneMultiFactorInfo
              }
            }
            PhoneAuthProvider.provider()
              .verifyPhoneNumber(with: selectedHint!, uiDelegate: nil,
                                 multiFactorSession: resolver
                                   .session) { verificationID, error in
                if error != nil {
                  print(
                    "Multi factor start sign in failed. Error: \(error.debugDescription)"
                  )
                } else {
                  self.showTextInputPrompt(
                    withMessage: "Verification code for \(selectedHint?.displayName ?? "")",
                    completionBlock: { userPressedOK, verificationCode in
                      let credential: PhoneAuthCredential? = PhoneAuthProvider.provider()
                        .credential(withVerificationID: verificationID!,
                                    verificationCode: verificationCode!)
                      let assertion: MultiFactorAssertion? = PhoneMultiFactorGenerator
                        .assertion(with: credential!)
                      resolver.resolveSignIn(with: assertion!) { authResult, error in
                        if error != nil {
                          print(
                            "Multi factor finanlize sign in failed. Error: \(error.debugDescription)"
                          )
                        } else {
                          self.navigationController?.popViewController(animated: true)
                        }
                      }
                    }
                  )
                }
              }
          }
        )
      } else {
        self.showMessagePrompt(error.localizedDescription)
        return
      }
      // ...
      return
    }
    // User is signed in
    // ...
}

Objective-C

[[FIRAuth auth] signInWithCredential:credential
                          completion:^(FIRAuthDataResult * _Nullable authResult,
                                       NSError * _Nullable error) {
    if (isMFAEnabled && error && error.code == FIRAuthErrorCodeSecondFactorRequired) {
      FIRMultiFactorResolver *resolver = error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey];
      NSMutableString *displayNameString = [NSMutableString string];
      for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {
        [displayNameString appendString:tmpFactorInfo.displayName];
        [displayNameString appendString:@" "];
      }
      [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Select factor to sign in\n%@", displayNameString]
                           completionBlock:^(BOOL userPressedOK, NSString *_Nullable displayName) {
       FIRPhoneMultiFactorInfo* selectedHint;
       for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {
         if ([displayName isEqualToString:tmpFactorInfo.displayName]) {
           selectedHint = (FIRPhoneMultiFactorInfo *)tmpFactorInfo;
         }
       }
       [FIRPhoneAuthProvider.provider
        verifyPhoneNumberWithMultiFactorInfo:selectedHint
        UIDelegate:nil
        multiFactorSession:resolver.session
        completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
          if (error) {
            [self showMessagePrompt:error.localizedDescription];
          } else {
            [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Verification code for %@", selectedHint.displayName]
                                 completionBlock:^(BOOL userPressedOK, NSString *_Nullable verificationCode) {
             FIRPhoneAuthCredential *credential =
                 [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationID
                                                              verificationCode:verificationCode];
             FIRMultiFactorAssertion *assertion = [FIRPhoneMultiFactorGenerator assertionWithCredential:credential];
             [resolver resolveSignInWithAssertion:assertion completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
               if (error) {
                 [self showMessagePrompt:error.localizedDescription];
               } else {
                 NSLog(@"Multi factor finanlize sign in succeeded.");
               }
             }];
           }];
          }
        }];
     }];
    }
  else if (error) {
    // ...
    return;
  }
  // User successfully signed in. Get user data from the FIRUser object
  if (authResult == nil) { return; }
  FIRUser *user = authResult.user;
  // ...
}];

下一步

用户首次登录后,会创建一个新用户帐户并将其链接到凭据(即用户名和密码、电话号码或身份验证提供商信息),即用户登录时使用的凭据。这个新帐户作为 Firebase 项目的一部分存储,可用于在项目中的每个应用中识别用户,无论用户如何登录。

  • 在您的应用程序中,您可以从FIRUser对象获取用户的基本个人资料信息。请参阅管理用户

  • 在您的 Firebase 实时数据库和云存储安全规则中,您可以从auth变量中获取登录用户的唯一用户 ID,并使用它来控制用户可以访问哪些数据。

您可以通过将身份验证提供程序凭据链接到现有用户帐户来允许用户使用多个身份验证提供程序登录您的应用程序。

要注销用户,请调用signOut:

迅速

    let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print("Error signing out: %@", signOutError)
}
  

Objective-C

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

您可能还想为所有身份验证错误添加错误处理代码。请参阅处理错误

,

您可以通过将 Google Sign-In 集成到您的应用中,让您的用户使用他们的 Google 帐户向 Firebase 进行身份验证。

在你开始之前

  1. 将 Firebase 添加到您的 Apple 项目中。在您的Podfile中包含以下 pod:
    pod 'FirebaseAuth'
    pod 'GoogleSignIn'
    
  2. 如果您尚未将应用连接到 Firebase 项目,请从Firebase 控制台执行此操作。
  3. 在 Firebase 控制台中启用 Google 作为登录方法:
    1. Firebase 控制台中,打开Auth部分。
    2. 登录方法选项卡上,启用Google登录方法并单击保存

1.导入需要的头文件

首先,您必须将 Firebase SDK 和 Google Sign-In SDK 头文件导入您的应用。

迅速

import FirebaseCore
import GoogleSignIn

Objective-C

@import FirebaseCore;
@import GoogleSignIn;

2. 实施谷歌登录

按照以下步骤实施 Google 登录。有关在 iOS 中使用 Google Sign-In 的详细信息,请参阅Google Sign-In 开发人员文档

  1. 将自定义 URL 方案添加到您的 Xcode 项目:
    1. 打开您的项目配置:双击左侧树视图中的项目名称。从TARGETS部分中选择您的应用程序,然后选择Info选项卡,然后展开URL Types部分。
    2. 单击+按钮,并为您的反向客户端 ID 添加 URL 方案。要查找此值,请打开GoogleService-Info.plist配置文件,然后查找REVERSED_CLIENT_ID键。复制该键的值,并将其粘贴到配置页面上的URL 方案框中。将其他字段留空。

      完成后,您的配置应类似于以下内容(但使用特定于应用程序的值):

  2. 在您的应用委托的application:didFinishLaunchingWithOptions:方法中,配置FirebaseApp对象。

    迅速

    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
    
  3. 实现应用程序委托的application:openURL:options:方法。该方法应调用GIDSignIn实例的handleURL方法,该方法将正确处理您的应用程序在身份验证过程结束时收到的 URL。

    迅速

    @available(iOS 9.0, *)
    func application(_ application: UIApplication, open url: URL,
                     options: [UIApplication.OpenURLOptionsKey: Any])
      -> Bool {
      return GIDSignIn.sharedInstance.handle(url)
    }
    

    Objective-C

    - (BOOL)application:(nonnull UIApplication *)application
                openURL:(nonnull NSURL *)url
                options:(nonnull NSDictionary<NSString *, id> *)options {
      return [[GIDSignIn sharedInstance] handleURL:url];
    }
    
  4. 将应用的呈现视图控制器和客户端 ID 传递给 Google Sign In 登录方法,并从生成的 Google 身份验证令牌创建 Firebase 身份验证凭据:

    迅速

    guard let clientID = FirebaseApp.app()?.options.clientID else { return }
    
    // Create Google Sign In configuration object.
    let config = GIDConfiguration(clientID: clientID)
    
    // Start the sign in flow!
    GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in
    
      if let error = error {
        // ...
        return
      }
    
      guard
        let authentication = user?.authentication,
        let idToken = authentication.idToken
      else {
        return
      }
    
      let credential = GoogleAuthProvider.credential(withIDToken: idToken,
                                                     accessToken: authentication.accessToken)
    
      // ...
    }
    

    Objective-C

    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID];
    
    __weak __auto_type weakSelf = self;
    [GIDSignIn.sharedInstance signInWithConfiguration:config presentingViewController:self callback:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
      __auto_type strongSelf = weakSelf;
      if (strongSelf == nil) { return; }
    
      if (error == nil) {
        GIDAuthentication *authentication = user.authentication;
        FIRAuthCredential *credential =
        [FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken
                                         accessToken:authentication.accessToken];
        // ...
      } else {
        // ...
      }
    }];
    
    
  5. GIDSignInButton添加到您的故事板、XIB 文件,或以编程方式对其进行实例化。要将按钮添加到情节提要或 XIB 文件,请添加一个 View 并将其自定义类设置为GIDSignInButton
  6. 可选:如果要自定义按钮,请执行以下操作:

    迅速

    1. 在您的视图控制器中,将登录按钮声明为属性。
      @IBOutlet weak var signInButton: GIDSignInButton!
    2. 将按钮连接到您刚刚声明的signInButton属性。
    3. 通过设置GIDSignInButton对象的属性来自定义按钮。

    Objective-C

    1. 在视图控制器的头文件中,将登录按钮声明为属性。
      @property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
    2. 将按钮连接到您刚刚声明的signInButton属性。
    3. 通过设置GIDSignInButton对象的属性来自定义按钮。

3. 使用 Firebase 进行身份验证

最后,使用上一步中创建的身份验证凭据完成 Firebase 登录过程。

迅速

Auth.auth().signIn(with: credential) { authResult, error in
    if let error = error {
      let authError = error as NSError
      if isMFAEnabled, authError.code == AuthErrorCode.secondFactorRequired.rawValue {
        // The user is a multi-factor user. Second factor challenge is required.
        let resolver = authError
          .userInfo[AuthErrorUserInfoMultiFactorResolverKey] as! MultiFactorResolver
        var displayNameString = ""
        for tmpFactorInfo in resolver.hints {
          displayNameString += tmpFactorInfo.displayName ?? ""
          displayNameString += " "
        }
        self.showTextInputPrompt(
          withMessage: "Select factor to sign in\n\(displayNameString)",
          completionBlock: { userPressedOK, displayName in
            var selectedHint: PhoneMultiFactorInfo?
            for tmpFactorInfo in resolver.hints {
              if displayName == tmpFactorInfo.displayName {
                selectedHint = tmpFactorInfo as? PhoneMultiFactorInfo
              }
            }
            PhoneAuthProvider.provider()
              .verifyPhoneNumber(with: selectedHint!, uiDelegate: nil,
                                 multiFactorSession: resolver
                                   .session) { verificationID, error in
                if error != nil {
                  print(
                    "Multi factor start sign in failed. Error: \(error.debugDescription)"
                  )
                } else {
                  self.showTextInputPrompt(
                    withMessage: "Verification code for \(selectedHint?.displayName ?? "")",
                    completionBlock: { userPressedOK, verificationCode in
                      let credential: PhoneAuthCredential? = PhoneAuthProvider.provider()
                        .credential(withVerificationID: verificationID!,
                                    verificationCode: verificationCode!)
                      let assertion: MultiFactorAssertion? = PhoneMultiFactorGenerator
                        .assertion(with: credential!)
                      resolver.resolveSignIn(with: assertion!) { authResult, error in
                        if error != nil {
                          print(
                            "Multi factor finanlize sign in failed. Error: \(error.debugDescription)"
                          )
                        } else {
                          self.navigationController?.popViewController(animated: true)
                        }
                      }
                    }
                  )
                }
              }
          }
        )
      } else {
        self.showMessagePrompt(error.localizedDescription)
        return
      }
      // ...
      return
    }
    // User is signed in
    // ...
}

Objective-C

[[FIRAuth auth] signInWithCredential:credential
                          completion:^(FIRAuthDataResult * _Nullable authResult,
                                       NSError * _Nullable error) {
    if (isMFAEnabled && error && error.code == FIRAuthErrorCodeSecondFactorRequired) {
      FIRMultiFactorResolver *resolver = error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey];
      NSMutableString *displayNameString = [NSMutableString string];
      for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {
        [displayNameString appendString:tmpFactorInfo.displayName];
        [displayNameString appendString:@" "];
      }
      [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Select factor to sign in\n%@", displayNameString]
                           completionBlock:^(BOOL userPressedOK, NSString *_Nullable displayName) {
       FIRPhoneMultiFactorInfo* selectedHint;
       for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {
         if ([displayName isEqualToString:tmpFactorInfo.displayName]) {
           selectedHint = (FIRPhoneMultiFactorInfo *)tmpFactorInfo;
         }
       }
       [FIRPhoneAuthProvider.provider
        verifyPhoneNumberWithMultiFactorInfo:selectedHint
        UIDelegate:nil
        multiFactorSession:resolver.session
        completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
          if (error) {
            [self showMessagePrompt:error.localizedDescription];
          } else {
            [self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Verification code for %@", selectedHint.displayName]
                                 completionBlock:^(BOOL userPressedOK, NSString *_Nullable verificationCode) {
             FIRPhoneAuthCredential *credential =
                 [[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationID
                                                              verificationCode:verificationCode];
             FIRMultiFactorAssertion *assertion = [FIRPhoneMultiFactorGenerator assertionWithCredential:credential];
             [resolver resolveSignInWithAssertion:assertion completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
               if (error) {
                 [self showMessagePrompt:error.localizedDescription];
               } else {
                 NSLog(@"Multi factor finanlize sign in succeeded.");
               }
             }];
           }];
          }
        }];
     }];
    }
  else if (error) {
    // ...
    return;
  }
  // User successfully signed in. Get user data from the FIRUser object
  if (authResult == nil) { return; }
  FIRUser *user = authResult.user;
  // ...
}];

下一步

用户首次登录后,会创建一个新用户帐户并将其链接到凭据(即用户名和密码、电话号码或身份验证提供商信息),即用户登录时使用的凭据。这个新帐户作为 Firebase 项目的一部分存储,可用于在项目中的每个应用中识别用户,无论用户如何登录。

  • 在您的应用程序中,您可以从FIRUser对象获取用户的基本个人资料信息。请参阅管理用户

  • 在您的 Firebase 实时数据库和云存储安全规则中,您可以从auth变量中获取登录用户的唯一用户 ID,并使用它来控制用户可以访问哪些数据。

您可以通过将身份验证提供程序凭据链接到现有用户帐户来允许用户使用多个身份验证提供程序登录您的应用程序。

要注销用户,请调用signOut:

迅速

    let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print("Error signing out: %@", signOutError)
}
  

Objective-C

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

您可能还想为所有身份验证错误添加错误处理代码。请参阅处理错误