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

您可以使用 Firebase Authentication 允許使用者透過一或多種登入方式登入應用程式,包括電子郵件地址和密碼登入,以及聯合身分識別提供者 (例如 Google 登入和 Facebook 登入)。本教學課程會介紹如何開始使用 Firebase Authentication,並說明如何在應用程式中加入電子郵件地址和密碼登入功能。

將應用程式連結至 Firebase

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

在應用程式中新增 Firebase Authentication

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

  1. 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」(檔案) 和「Add Packages」(新增 Package)
  2. 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. 選擇 Firebase Authentication 程式庫。
  5. -ObjC 標記新增至目標建構設定的「Other Linker Flags」部分。
  6. 完成後,Xcode 會自動開始在背景中解析並下載依附元件。

(選用) 使用 Firebase Local Emulator Suite 製作原型並進行測試

在說明應用程式如何驗證使用者之前,我們先介紹一組可用於原型設計和測試 Authentication 功能的工具:Firebase Local Emulator Suite。如果您正在決定要使用哪種驗證技術和供應商、嘗試使用 AuthenticationFirebase Security Rules 搭配公開和私人資料的不同資料模型,或是製作登入 UI 設計的原型,那麼在不部署即時服務的情況下,於本機作業會是個好主意。

Authentication模擬器是 Local Emulator Suite 的一部分,可讓應用程式與模擬的資料庫內容和設定互動,以及選擇性地與模擬的專案資源 (函式、其他資料庫和安全性規則) 互動。

使用 Authentication 模擬器只需幾個步驟:

  1. 在應用程式的測試設定中加入一行程式碼,即可連線至模擬器。
  2. 從本機專案目錄的根目錄執行 firebase emulators:start
  3. 使用 Local Emulator Suite UI 進行互動式原型設計,或使用 Authentication 模擬器 REST API 進行非互動式測試。

如需詳細指南,請參閱「將應用程式連線至 Authentication 模擬器」。詳情請參閱Local Emulator Suite簡介

接下來,我們將繼續說明如何驗證使用者。

初始化 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;
  // ...
}

後續步驟

瞭解如何新增其他身分識別提供者和匿名訪客帳戶的支援功能: