您可以通过将 Google Sign-In 集成到您的应用中,让您的用户使用他们的 Google 帐户通过 Firebase 进行身份验证。
在你开始之前
- 将 Firebase 添加到您的 Apple 项目。在
Podfile
中包含以下 pod:pod 'FirebaseAuth' pod 'GoogleSignIn'
- 如果您尚未将您的应用程序连接到您的 Firebase 项目,请从Firebase 控制台执行此操作。
- 在 Firebase 控制台中启用 Google 作为登录方法:
- 在Firebase 控制台中,打开Auth部分。
- 在登录方法选项卡上,启用Google登录方法并单击保存。
1.导入需要的头文件
首先,您必须将 Firebase SDK 和 Google Sign-In SDK 头文件导入您的应用程序。
迅速
import FirebaseCore import GoogleSignIn
目标-C
@import FirebaseCore; @import GoogleSignIn;
2.实现谷歌登录
按照以下步骤实施 Google 登录。有关在 iOS 上使用 Google 登录的详细信息,请参阅Google 登录开发人员文档。
- 将自定义 URL 方案添加到您的 Xcode 项目:
- 打开您的项目配置:双击左侧树视图中的项目名称。从TARGETS部分选择您的应用程序,然后选择Info选项卡,并展开URL Types部分。
- 单击+按钮,并为您的反向客户端 ID 添加 URL 方案。要查找此值,请打开
配置文件,然后查找GoogleService-Info.plist REVERSED_CLIENT_ID
键。复制该键的值,并将其粘贴到配置页面上的URL Schemes框中。将其他字段留空。完成后,您的配置应类似于以下内容(但具有特定于应用程序的值):
- 在您的应用委托的
application:didFinishLaunchingWithOptions:
方法中,配置FirebaseApp
对象。迅速
// Use Firebase library to configure APIs FirebaseApp.configure()
目标-C
// Use Firebase library to configure APIs [FIRApp configure];
- 实施
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) }
目标-C
- (BOOL)application:(nonnull UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<NSString *, id> *)options { return [[GIDSignIn sharedInstance] handleURL:url]; }
- 将应用程序的呈现视图控制器和客户端 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) // ... }
目标-C
GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID]; [GIDSignIn.sharedInstance setConfiguration:config]; __weak __auto_type weakSelf = self; [GIDSignIn.sharedInstance signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable result, NSError * _Nullable error) { __auto_type strongSelf = weakSelf; if (strongSelf == nil) { return; } if (error == nil) { FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:result.user.idToken.tokenString accessToken:result.user.accessToken.tokenString]; // ... } else { // ... } }];
- 将
GIDSignInButton
添加到故事板、XIB 文件,或以编程方式实例化它。要将按钮添加到故事板或 XIB 文件,请添加一个视图并将其自定义类设置为GIDSignInButton
。 - 可选:如果要自定义按钮,请执行以下操作:
迅速
- 在您的视图控制器中,将登录按钮声明为属性。
@IBOutlet weak var signInButton: GIDSignInButton!
- 将按钮连接到您刚刚声明的
signInButton
属性。 - 通过设置GIDSignInButton对象的属性来自定义按钮。
目标-C
- 在视图控制器的头文件中,将登录按钮声明为属性。
@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
- 将按钮连接到您刚刚声明的
signInButton
属性。 - 通过设置GIDSignInButton对象的属性来自定义按钮。
- 在您的视图控制器中,将登录按钮声明为属性。
3. 使用 Firebase 进行身份验证
最后,使用上一步创建的 auth 凭据完成 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 // ... }
目标-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 项目的一部分,可用于在项目中的每个应用程序中识别用户,无论用户如何登录。
在您的 Firebase Realtime Database 和 Cloud Storage Security Rules中,您可以从
auth
变量中获取登录用户的唯一用户 ID,并使用它来控制用户可以访问哪些数据。
您可以允许用户使用多个身份验证提供程序登录您的应用程序,方法是将身份验证提供程序凭据链接到现有用户帐户。
要注销用户,请调用signOut:
。
迅速
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
目标-C
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
您可能还想为所有身份验证错误添加错误处理代码。请参阅处理错误。