開始在 Apple 平台上使用 Firebase 驗證

您可透過 Firebase 驗證功能,讓使用者使用 更多登入方式,包括電子郵件地址和密碼登入 聯合識別資訊提供者,例如 Google 登入和 Facebook 登入。這個 教學課程會介紹如何使用 Firebase 驗證功能 電子郵件地址和密碼登入應用程式。

將應用程式連結至 Firebase

  1. 安裝 Firebase SDK
  2. Firebase 主控台內,將您的應用程式新增至 Firebase 專案中。

在應用程式中加入 Firebase 驗證

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

  1. 在 Xcode 中保持開啟應用程式專案,然後依序選擇 [檔案] >新增套件
  2. 在系統提示時,新增 Firebase Apple 平台 SDK 存放區:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. 選擇 Firebase 驗證資料庫。
  5. 在目標建構設定的「Other Linker Flags」部分中新增 -ObjC 標記。
  6. 完成後,Xcode 會自動開始解析並下載 複製到背景依附元件

(選用) 使用 Firebase 本機模擬器套件設計原型並進行測試

在說明應用程式如何驗證使用者之前,我們先介紹一組 可用來設計驗證原型及測試驗證功能的工具: Firebase 本機模擬器套件。如果你正在考慮採用驗證方法 並嘗試運用公開和私人資料,嘗試不同的資料模型 運用驗證和 Firebase 安全性規則,或是設計登入使用者介面的原型, 無需部署有效服務就在本機上運作,會是個好主意。

驗證模擬器屬於本機模擬器套件的一部分, 可讓應用程式與模擬的資料庫內容和設定互動,例如: 以及選用的模擬專案資源 (函式、其他資料庫 和安全性規則)。

使用驗證模擬器只需完成幾個步驟:

  1. 將一行程式碼新增至應用程式的測試設定,即可與模擬器連線。
  2. 從本機專案目錄的根目錄中執行 firebase emulators:start
  3. 使用本機模擬器套件 UI 進行互動式原型設計,或 驗證模擬器 REST API,用於非互動式測試。

如需詳細指南,請參閱「將應用程式連線至驗證模擬器」一文。 詳情請參閱「本機模擬器套件簡介」。

接下來說明如何驗證使用者。

初始化 Firebase SDK

在應用程式委派項目中,先匯入 Firebase SDK:

Swift

import FirebaseCore

Objective-C

@import FirebaseCore;

接著,在 application:didFinishLaunchingWithOptions: 方法中,初始化 FirebaseApp 物件:

Swift

// Use Firebase library to configure APIs
FirebaseApp.configure()

Objective-C

// Use Firebase library to configure APIs
[FIRApp configure];

監聽驗證狀態

針對每個需要登入使用者相關資訊的應用程式檢視畫面, 將事件監聽器附加至 FIRAuth 物件。系統會呼叫這個事件監聽器 使用者的登入狀態變更。

在檢視控制器的 viewWillAppear 方法中附加事件監聽器:

Swift

handle = Auth.auth().addStateDidChangeListener { auth, user in
  // ...
}

Objective-C

self.handle = [[FIRAuth auth]
    addAuthStateDidChangeListener:^(FIRAuth *_Nonnull auth, FIRUser *_Nullable user) {
      // ...
    }];

然後在檢視控制器的 viewWillDisappear 方法中卸離事件監聽器:

Swift

Auth.auth().removeStateDidChangeListener(handle!)

Objective-C

[[FIRAuth auth] removeAuthStateDidChangeListener:_handle];

註冊新使用者

建立表單,讓新使用者透過電子郵件使用您的應用程式註冊 位址和密碼使用者填妥表單後,請驗證電子郵件 地址和密碼,然後將這些資料傳遞至 createUser 方法:

Swift

Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
  // ...
}

Objective-C

[[FIRAuth auth] createUserWithEmail:email
                           password:password
                         completion:^(FIRAuthDataResult * _Nullable authResult,
                                      NSError * _Nullable error) {
  // ...
}];

登入現有使用者

建立表單,讓現有使用者透過他們的電子郵件地址登入 和密碼。使用者填妥表單時,請呼叫 signIn 方法:

Swift

Auth.auth().signIn(withEmail: email, password: password) { [weak self] authResult, error in
  guard let strongSelf = self else { return }
  // ...
}

Objective-C

[[FIRAuth auth] signInWithEmail:self->_emailField.text
                       password:self->_passwordField.text
                     completion:^(FIRAuthDataResult * _Nullable authResult,
                                  NSError * _Nullable error) {
  // ...
}];

取得使用者資訊

使用者成功登入後,您就可以取得使用者的相關資訊。適用對象 例如在驗證狀態事件監聽器中:

Swift

if let user = user {
  // The user's ID, unique to the Firebase project.
  // Do NOT use this value to authenticate with your backend server,
  // if you have one. Use getTokenWithCompletion:completion: instead.
  let uid = user.uid
  let email = user.email
  let photoURL = user.photoURL
  var multiFactorString = "MultiFactor: "
  for info in user.multiFactor.enrolledFactors {
    multiFactorString += info.displayName ?? "[DispayName]"
    multiFactorString += " "
  }
  // ...
}

Objective-C

if (user) {
  // The user's ID, unique to the Firebase project.
  // Do NOT use this value to authenticate with your backend server,
  // if you have one. Use getTokenWithCompletion:completion: instead.
  NSString *email = user.email;
  NSString *uid = user.uid;
  NSMutableString *multiFactorString = [NSMutableString stringWithFormat:@"MultiFactor: "];
  for (FIRMultiFactorInfo *info in user.multiFactor.enrolledFactors) {
    [multiFactorString appendString:info.displayName];
    [multiFactorString appendString:@" "];
  }
  NSURL *photoURL = user.photoURL;
  // ...
}

後續步驟

瞭解如何新增對其他識別資訊提供者和匿名訪客的支援 帳戶: