在 Apple 平台上以匿名方式透過 Firebase 驗證

您可以使用 Firebase Authentication 建立及使用臨時匿名帳戶,以便透過 Firebase 進行驗證。這些臨時匿名帳戶可讓尚未註冊應用程式的使用者,使用受安全性規則保護的資料。如果匿名使用者決定註冊您的應用程式,您可以將他們的登入憑證連結至匿名帳戶,讓他們在日後的工作階段繼續使用受保護的資料。

事前準備

  1. 使用 Swift Package Manager 安裝及管理 Firebase 依附元件。

    1. 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」>「Add Packages」
    2. 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
    3.   https://github.com/firebase/firebase-ios-sdk.git
    4. 選擇 Firebase Authentication 程式庫。
    5. -ObjC 標記新增至目標的建構設定「Other Linker Flags」部分。
    6. 完成後,Xcode 就會自動開始在背景中解析並下載依附元件。
  2. 如果您尚未將應用程式連結至 Firebase 專案,請透過 Firebase 主控台連結。
  3. 啟用匿名驗證:
    1. Firebase 控制台中,開啟「Auth」部分。
    2. 在「Sign-in Methods」頁面中,啟用「Anonymous」登入方法。
    3. 選用:如果您已將專案升級至 Firebase Authentication with Identity Platform,可以啟用自動清理功能。啟用這項設定後,系統就會自動刪除建立至今超過 30 天的匿名帳戶。在啟用自動清理功能的專案中,匿名驗證功能就不會計入用量限制或計費配額。請參閱「自動清理」一文。

以匿名身分驗證 Firebase

如果已登出的使用者使用需要透過 Firebase 驗證的應用程式功能,請完成下列步驟,讓使用者以匿名身分登入:

  1. UIApplicationDelegate 中匯入 FirebaseCore 模組,以及應用程式委派程式使用的任何其他 Firebase 模組。例如,如要使用 Cloud FirestoreAuthentication
    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  2. 在應用程式委派作業的 application(_:didFinishLaunchingWithOptions:) 方法中,設定 FirebaseApp 共用例項:
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    // Use Firebase library to configure APIs
    [FIRApp configure];
  3. 如果您使用 SwiftUI,則必須建立應用程式委派程式,並透過 UIApplicationDelegateAdaptorNSApplicationDelegateAdaptor 將其附加至 App 結構體。您也必須停用應用程式委派程式 swizzling。詳情請參閱 SwiftUI 操作說明
    SwiftUI
    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          
  4. 呼叫 signInAnonymouslyWithCompletion: 方法:
    SwiftObjective-C
    Auth.auth().signInAnonymously { authResult, error in
      // ...
    }
    [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult * _Nullable authResult,
                                                      NSError * _Nullable error) {
       // ...
     }];
  5. 如果 signInAnonymouslyWithCompletion: 方法完成且沒有錯誤,您可以從 FIRAuthDataResult 物件取得匿名使用者的帳戶資料:
    SwiftObjective-C
    guard let user = authResult?.user else { return }
    let isAnonymous = user.isAnonymous  // true
    let uid = user.uid
    FIRUser *user = authResult.user;
    BOOL isAnonymous = user.anonymous;  // YES
    NSString *uid = user.uid;

將匿名帳戶轉換為永久帳戶

當匿名使用者註冊應用程式時,您可能會想讓他們繼續使用新帳戶進行工作。舉例來說,您可以讓使用者在註冊前將商品加入購物車,並在他們的新帳戶購物車中顯示這些商品。如要這樣做,請完成下列步驟:

  1. 使用者註冊時,請完成使用者驗證提供者的登入流程,但不包括呼叫其中一個 FIRAuth.signInWith 方法。例如取得使用者的 Google ID 權杖、Facebook 存取權杖,或電子郵件地址和密碼。
  2. 取得新驗證供應器的 FIRAuthCredential

    Google 登入
    SwiftObjective-C
    guard
      let authentication = user?.authentication,
      let idToken = authentication.idToken
    else {
      return
    }
    
    let credential = GoogleAuthProvider.credential(withIDToken: idToken,
                                                   accessToken: authentication.accessToken)
    FIRAuthCredential *credential =
    [FIRGoogleAuthProvider credentialWithIDToken:result.user.idToken.tokenString
                                     accessToken:result.user.accessToken.tokenString];
    Facebook 登入
    SwiftObjective-C
    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
    電子郵件地址和密碼登入
    SwiftObjective-C
    let credential = EmailAuthProvider.credential(withEmail: email, password: password)
    FIRAuthCredential *credential =
        [FIREmailAuthProvider credentialWithEmail:email
                                                 password:password];
  3. FIRAuthCredential 物件傳遞至登入使用者的 linkWithCredential:completion: 方法:

    SwiftObjective-C
        user.link(with: credential) { authResult, error in
      // ...
    }
    }
        [[FIRAuth auth].currentUser linkWithCredential:credential
        completion:^(FIRAuthDataResult *result, NSError *_Nullable error) {
      // ...
    }];

如果對 linkWithCredential:completion: 的呼叫成功,使用者的新帳戶就能存取匿名帳戶的 Firebase 資料。

自動清除

如果您已將專案升級至 Firebase Authentication with Identity Platform,可以在 Firebase 主控台中啟用自動清理功能。啟用這項功能後,Firebase 就會自動刪除建立至今超過 30 天的匿名帳戶。在啟用自動清理功能的專案中,匿名驗證不會計入用量限制或計費配額。

  • 啟用自動清理功能後建立的所有匿名帳戶,可能會在建立後 30 天後的任何時間自動刪除。
  • 啟用自動清理功能後,現有的匿名帳戶會在 30 天後自動刪除。
  • 如果您關閉自動清理功能,所有已排定要刪除的匿名帳戶都會維持原先的刪除排程。
  • 如果您將匿名帳戶連結至任何登入方式,系統就不會自動刪除該帳戶。

如果您想在啟用這項功能前查看有多少使用者會受到影響,且已將專案升級至 Firebase Authentication with Identity Platform,您可以在 Cloud Logging 中依 is_anon 篩選。

後續步驟

使用者現在可以透過 Firebase 進行驗證,您可以使用 Firebase 規則控制使用者對 Firebase 資料庫中資料的存取權。

Firebase Authentication lets you add an end-to-end identity solution to your app for easy user authentication, sign-in, and onboarding in just a few lines of code.

更新時間:Mar 7, 2025