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

您可以使用 Firebase Authentication 來建立和使用臨時匿名帳戶 使用 Firebase 進行驗證這些暫時的匿名帳戶 讓尚未註冊應用程式的使用者與資料受到妥善保護 並限制安全性規則如果匿名使用者決定註冊您的應用程式,您可以 將他們的登入憑證連結至匿名的 帳戶,方便他們在 稍後的工作階段

事前準備

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

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

透過 Firebase 匿名驗證

使用者在未登入狀態下使用需要進行身分驗證的應用程式功能時 Firebase 完成下列步驟,以匿名方式登入使用者:

  1. FirebaseCore 模組匯入至 UIApplicationDelegate和任何其他 應用程式委派所用的 Firebase 模組。 例如,如要使用 Cloud FirestoreAuthentication
    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          
    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  2. 設定 FirebaseApp敬上 共用執行個體 application(_:didFinishLaunchingWithOptions:) 方法:
    // 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,則必須建立並附加應用程式委派 透過 UIApplicationDelegateAdaptorApp NSApplicationDelegateAdaptor。您也必須停用應用程式委派功能切換功能。適用對象 詳情請參閱 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,並依據下列條件進行篩選: 雲端中的 is_anon 記錄

後續步驟

使用者現在可以透過 Firebase 進行驗證,因此你可以控管他們 訓練資料使用 Firebase 規則

Firebase gives you the tools and infrastructure you need to build better mobile and web apps, improve app quality, and grow your business.

更新時間:Feb 28, 2025