您可以將 Google 登入整合至應用程式,讓使用者使用 Google 帳戶進行 Firebase 驗證。
事前準備
使用 Swift Package Manager 安裝及管理 Firebase 依附元件。
- 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」>「Add Packages」。
- 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
- 選擇 Firebase Authentication 程式庫。
- 將
-ObjC
標記新增至目標的建構設定「Other Linker Flags」部分。 - 完成後,Xcode 就會自動開始在背景中解析並下載依附元件。
https://github.com/firebase/firebase-ios-sdk.git
在專案中加入 Google 登入 SDK
在 Xcode 中保持開啟應用程式專案,然後依序點選「File」>「Add Packages」。
系統提示時,請新增 Google 登入 SDK 存放區:
https://github.com/google/GoogleSignIn-iOS
完成後,Xcode 就會自動開始在背景中解析並下載依附元件。
為 Firebase 專案啟用 Google 登入
如要允許使用者使用 Google 登入功能登入,您必須先為 Firebase 專案啟用 Google 登入供應器:
- 在 Firebase 主控台中,開啟「驗證」部分。
- 在「登入方式」分頁中,啟用 Google 供應器。
按一下 [儲存]。
下載專案
GoogleService-Info.plist
檔案的新副本,然後複製到 Xcode 專案。使用新版本覆寫任何現有版本。(請參閱「將 Firebase 新增至 iOS 專案」)。
匯入必要的標頭檔案
首先,您必須將 Firebase SDK 和 Google 登入 SDK 標頭檔案匯入應用程式。
import FirebaseCore import FirebaseAuth import GoogleSignIn
@import FirebaseCore; @import GoogleSignIn;
設定 Google 登入
請按照下列步驟實作 Google 登入功能。如要進一步瞭解如何在 iOS 上使用 Google 登入,請參閱 Google 登入開發人員說明文件。
- 在 Xcode 專案中新增自訂網址配置:
- 開啟專案設定:按一下左側樹狀檢視中的專案名稱。從「TARGETS」部分選取應用程式,然後選取「Info」分頁標籤,並展開「URL Types」部分。
- 按一下「+」按鈕,然後為已反轉的用戶端 ID 新增網址配置。如要找出這個值,請開啟
設定檔,然後尋找GoogleService-Info.plist REVERSED_CLIENT_ID
鍵。複製該鍵的值,然後貼到設定頁面上的「網址配置」方塊中。請勿修改其他欄位。完成後,設定應類似於下列內容 (但會顯示應用程式專屬的值):
- 在應用程式委派作業的
application:didFinishLaunchingWithOptions:
方法中,設定FirebaseApp
物件。FirebaseApp.configure()
// Use Firebase library to configure APIs [FIRApp configure];
- 實作應用程式委派作業的
application:openURL:options:
方法。該方法應呼叫GIDSignIn
例項的handleURL
方法,該方法會正確處理應用程式在驗證程序結束時收到的網址。func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { return GIDSignIn.sharedInstance.handle(url) }
- (BOOL)application:(nonnull UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<NSString *, id> *)options { return [[GIDSignIn sharedInstance] handleURL:url]; }
- 將應用程式的呈現 View Controller 和用戶端 ID 傳遞至 Google 登入服務供應器的
signIn
方法,並根據產生的 Google 驗證權杖建立 Firebase 驗證憑證:guard let clientID = FirebaseApp.app()?.options.clientID else { return } // Create Google Sign In configuration object. let config = GIDConfiguration(clientID: clientID) GIDSignIn.sharedInstance.configuration = config // Start the sign in flow! GIDSignIn.sharedInstance.signIn(withPresenting: self) { [unowned self] result, error in guard error == nil else { // ... } guard let user = result?.user, let idToken = user.idToken?.tokenString else { // ... } let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: user.accessToken.tokenString) // ... }
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 檔案,請新增 View,並將其自訂類別設為GIDSignInButton
。 - 選用:如要自訂按鈕,請按照下列步驟操作:
- 在 View Controller 中,將登入按鈕宣告為屬性。
@IBOutlet weak var signInButton: GIDSignInButton!
- 將按鈕連結至您剛才宣告的
signInButton
屬性。 - 設定 GIDSignInButton 物件的屬性,即可自訂按鈕。
- 在 View Controller 的標頭檔案中,將登入按鈕宣告為屬性。
@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
- 將按鈕連結至您剛才宣告的
signInButton
屬性。 - 設定 GIDSignInButton 物件的屬性,即可自訂按鈕。
- 在 View Controller 中,將登入按鈕宣告為屬性。
使用 Firebase 進行驗證
最後,請使用上一個步驟建立的驗證憑證,完成 Firebase 登入程序。
Auth.auth().signIn(with: credential) { result, error in // At this point, our user is signed in }
[[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 安全性規則中,您可以從
auth
變數取得已登入使用者的專屬使用者 ID,並利用該 ID 控管使用者可存取的資料。
您可以將驗證服務供應商憑證連結至現有使用者帳戶,讓使用者使用多個驗證服務供應商登入應用程式。
如要讓使用者登出,請呼叫
signOut:
。
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
您可能還想為各種驗證錯誤新增錯誤處理程式碼。請參閱「處理錯誤」。