owned this note
owned this note
Published
Linked with GitHub
###### tags: `第13屆IT邦鐵人賽文章`
# 【在 iOS 開發路上的大小事-Day15】透過 Firebase 來管理使用者 (Sign in with E-mail 篇) Part1
這篇會來教大家如何透過 Firebase 在你的 iOS App 上實作註冊以及登入功能
透過 Firebase 在你的 iOS App 上實作登出以及密碼重設功能會放在下一篇喔
# 前置作業
打開專案的 Podfile,新增 Firebase/Auth
```
pod 'Firebase/Auth'
```

```
pod install
```

接著到該專案的 Firebase Console 裡點左側的「Authentication」,再點「Sign-in method」,將「電子郵件/密碼」這個選項開啟

# 開始實作囉
打開 `專案名稱.xcworkspace`,然後在你需要用到的檔案引入 Firebase
```swift=
import Firebase
import FirebaseAuth
```
首先先將帳號跟密碼的 TextField、帳號登入的 Button 的 IBOutlet 拉好
以及宣告一個變數 isSignIn,型別為 Bool,初始值為 false,用來判斷是否已經登入
```swift=
@IBOutlet weak var accountTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var signInOrSignOutBtn: UIButton!
var isSignIn: Bool = false
```
然後在註冊帳號按鈕的 IBAction 加入下面這段
我們先判斷是否任一帳號欄位為空,為空的話,就通知說「請輸入帳號!」
不為空的話,就透過 Firebase 提供的 createUser() API,來實作註冊帳號功能
```swift=
@IBAction func registerAccount(_ sender: UIButton) {
if (accountTF.text == "") {
CustomFunc.customAlert(title: "請輸入帳號!", message: "", vc: self, actionHandler: nil)
} else {
Auth.auth().createUser(withEmail:accountTF.text!, password: passwordTF.text!) { (user, error) in
if (error == nil) {
CustomFunc.customAlert(title: "帳號已成功建立!", message: "", vc: self, actionHandler: nil)
} else {
CustomFunc.customAlert(title: "", message: "\(String(describing: error!.localizedDescription))", vc: self, actionHandler: nil)
}
}
}
}
```
註冊完之後,就可以在 Firebase Console 裡看到剛剛我們註冊的帳號了

接著在帳號登入按鈕的 IBAction 加入下面這段
我們先判斷目前是否有使用者存在
假設有的話,就執行帳號登出功能,沒有的話,就執行帳號登入功能,這裡我們先實作帳號登入功能
接著我們先判斷是否任一帳號密碼欄位為空,為空的話,就通知說「請重新輸入帳號密碼!」
不為空的話,就透過 Firebase 提供的 signIn() API,來實作帳號登入功能
```swift=
@IBAction func accountSignInOrSignOut(_ sender: UIButton) {
if (Auth.auth().currentUser == nil || !isSignIn) {
// 無用戶登入
if (accountTF.text == "" || passwordTF.text == "") {
CustomFunc.customAlert(title: "請重新輸入帳號密碼!", message: "", vc: self, actionHandler: nil)
} else {
Auth.auth().signIn(withEmail:accountTF.text!, password: passwordTF.text!) { (user, error) in
guard error == nil else {
CustomFunc.customAlert(title: "", message: "\(String(describing: error!.localizedDescription))", vc: self, actionHandler: nil)
return
}
CustomFunc.customAlert(title: "登入成功!", message: "", vc: self, actionHandler: self.getFirebaseUserInfo)
self.accountTF.text = ""
self.passwordTF.text = ""
self.isSignIn = true
self.signInOrSignOutBtn.setTitle("帳號登出", for: .normal)
}
}
} else {
// 有用戶登入
// 登出功能,下一篇才會教喔!
}
}
```
帳號登出、密碼重設功能就留到明天再說囉~
本篇的參考範例程式碼:[Github](https://github.com/leoho0722/IT2021/blob/main/Day15~Day22%E3%80%81Day24~Day28/CocoaPodsDemo/CocoaPodsDemo/FirebaseVC/EmailVC/EmailVC.swift)