透過將 Google 登入整合到您的應用程式中,您可以讓使用者使用其 Google 帳戶透過 Firebase 進行身份驗證。
在你開始之前
使用 Swift Package Manager 安裝和管理 Firebase 相依性。
- 在 Xcode 中,開啟應用程式項目,導覽至File > Add Packages 。
- 出現提示時,新增 Firebase Apple 平台 SDK 儲存庫:
- 選擇 Firebase 身份驗證庫。
- 將
-ObjC
標誌新增至目標建置設定的「其他連結器標誌」部分。 - 完成後,Xcode 將自動開始在背景解析並下載您的依賴項。
https://github.com/firebase/firebase-ios-sdk.git
將 Google 登入 SDK 新增至您的項目
在 Xcode 中,開啟應用程式項目,導覽至File > Add Packages 。
出現提示時,新增 Google Sign-In SDK 儲存庫:
https://github.com/google/GoogleSignIn-iOS
完成後,Xcode 將自動開始在背景解析並下載您的依賴項。
為您的 Firebase 專案啟用 Google 登入
若要允許使用者使用 Google Sign-In 登錄,您必須先為您的 Firebase 專案啟用 Google Sign-In 提供者:
- 在Firebase 控制台中,開啟「驗證」部分。
- 在登入方法標籤上,啟用Google提供者。
按一下「儲存」 。
下載專案的
GoogleService-Info.plist
檔案的新副本並將其複製到您的 Xcode 專案。用新版本覆蓋任何現有版本。 (請參閱將 Firebase 新增至您的 iOS 專案。)
導入需要的頭文件
首先,您必須將 Firebase SDK 和 Google Sign-In SDK 頭檔匯入到您的應用程式中。
迅速
import FirebaseCore import FirebaseAuth import GoogleSignIn
Objective-C
@import FirebaseCore; @import GoogleSignIn;
實施 Google 登入
請依照以下步驟實施 Google 登入。有關在 iOS 上使用Google 登入的詳細信息,請參閱 Google 登入開發人員文件。
- 將自訂 URL 方案新增至您的 Xcode 專案:
- 開啟您的專案配置:點選左側樹視圖中的項目名稱。從“目標”部分選擇您的應用程序,然後選擇“資訊”選項卡,並展開“URL 類型”部分。
- 按一下+按鈕,並為反向用戶端 ID 新增 URL 方案。若要尋找此值,請開啟
設定文件,然後尋找GoogleService-Info.plist REVERSED_CLIENT_ID
鍵。複製該鍵的值,並將其貼上到設定頁面上的URL 方案框中。保持其他欄位不變。完成後,您的配置應類似於以下內容(但具有特定於應用程式的值):
- 在應用程式委託的
application:didFinishLaunchingWithOptions:
方法中,配置FirebaseApp
物件。迅速
FirebaseApp.configure()
Objective-C
// Use Firebase library to configure APIs [FIRApp configure];
- 實作應用程式委託的
application:openURL:options:
方法。此方法應呼叫GIDSignIn
實例的handleURL
方法,該方法將正確處理應用程式在驗證過程結束時收到的 URL。迅速
func application(_ app: 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]; }
- 將應用程式的呈現視圖控制器和用戶端 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) // ... }
Objective-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物件的屬性來自訂按鈕。
Objective-C
- 在視圖控制器的頭檔中,將登入按鈕宣告為屬性。
@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;
- 將按鈕連接到您剛剛聲明的
signInButton
屬性。 - 透過設定GIDSignInButton物件的屬性來自訂按鈕。
- 在視圖控制器中,將登入按鈕聲明為屬性。
使用 Firebase 進行身份驗證
最後,使用上一個步驟中建立的身份驗證憑證完成 Firebase 登入程序。
迅速
Auth.auth().signIn(with: credential) { result, error in // At this point, our 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 專案的一部分存儲,並且可用於識別專案中每個應用程式中的用戶,無論用戶如何登入。
在 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; }
您可能還需要為所有身份驗證錯誤新增錯誤處理代碼。請參閱處理錯誤。