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

您可以使用 Firebase 驗證,允許使用者使用一種或多種登入方法登入您的應用程式,包括電子郵件地址和密碼登錄,以及聯合身分提供者(例如 Google 登入和 Facebook 登入)。本教學向您展示如何為您的應用程式新增電子郵件地址和密碼登錄,協助您開始使用 Firebase 身份驗證。

將您的應用程式連接到 Firebase

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

將 Firebase 身份驗證新增至您的應用

使用 Swift Package Manager 安裝和管理 Firebase 相依性。

  1. 在 Xcode 中,開啟應用程式項目,導覽至File > Add Packages
  2. 出現提示時,新增 Firebase Apple 平台 SDK 儲存庫:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. 選擇 Firebase 身份驗證庫。
  5. -ObjC標誌新增至目標建置設定的「其他連結器標誌」部分。
  6. 完成後,Xcode 將自動開始在背景解析並下載您的依賴項。

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

在討論您的應用程式如何對使用者進行身份驗證之前,我們先介紹一組可用於原型設計和測試身份驗證功能的工具:Firebase Local Emulator Suite。如果您正在選擇身份驗證技術和提供者,使用身份驗證和Firebase 安全性規則嘗試使用公共和私有資料的不同資料模型,或者對登入UI 設計進行原型設計,那麼能夠在本地工作而無需部署即時服務可能是一個好主意。

身份驗證模擬器是本機模擬器套件的一部分,它使您的應用程式能夠與模擬資料庫內容和配置以及可選的模擬項目資源(函數、其他資料庫和安全規則)進行互動。

使用身份驗證模擬器只需幾個步驟:

  1. 將一行程式碼新增至應用程式的測試配置以連接到模擬器。
  2. 從本地專案目錄的根目錄中,運行firebase emulators:start
  3. 使用本機模擬器套件 UI 進行互動式原型設計,或使用驗證模擬器 REST API 進行非互動式測試。

詳細指南可在將您的應用程式連接到身份驗證模擬器中找到。有關詳細信息,請參閱本地模擬器套件簡介

現在讓我們繼續了解如何對使用者進行身份驗證。

初始化 Firebase SDK

在您的應用程式委託中,首先導入 Firebase SDK:

迅速

import FirebaseCore

Objective-C

@import FirebaseCore;

然後,在application:didFinishLaunchingWithOptions:方法中,初始化FirebaseApp物件:

迅速

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

Objective-C

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

監聽認證狀態

對於需要有關登入使用者資訊的每個應用程式視圖,請將偵聽器附加到FIRAuth物件。每當使用者的登入狀態發生變更時,都會呼叫此偵聽器。

在視圖控制器的viewWillAppear方法中附加監聽器:

迅速

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

Objective-C

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

並在視圖控制器的viewWillDisappear方法中分離監聽器:

迅速

Auth.auth().removeStateDidChangeListener(handle!)

Objective-C

[[FIRAuth auth] removeAuthStateDidChangeListener:_handle];

註冊新用戶

建立一個表單,允許新使用者使用他們的電子郵件地址和密碼在您的應用程式中註冊。當使用者填寫表單時,請驗證使用者提供的電子郵件地址和密碼,然後將它們傳遞給createUser方法:

迅速

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方法:

迅速

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) {
  // ...
}];

獲取用戶資訊

用戶登入成功後,您可以獲得該用戶的資訊。例如,在您的身份驗證狀態偵聽器中:

迅速

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

下一步

了解如何新增對其他身分提供者和匿名訪客帳號的支援: