因為昨天安裝了Firebase的資料庫,那麼今天就來使用Firebase實作登入畫面的操作
// 在podfile內
pod 'Firebase/Auth'
// 在Terminal內移動至專案的資料夾
pod install
// 會安裝Firebase/auth
// 透過import 來使用SDK
import FirebaseAuth
@IBAction func Register(_ sender: Any){
// 透過使用UIAlert的出現來註冊帳號,驗證帳號密碼的書寫錯誤的部分則由Firebase來執行
// 使用UIAlert必須先有一個UIAlertController
let RegisterAlert = UIAlertController(title:"註冊",message:"",preferredStyle: .alert)
// 註冊的UIAlertAction
let RegisterAction = UIAlertAction(title: "Register Right Now", style: .default){
// 使用Closure
(action) in
let emailtextfield = RegisterAlert.textFields![0]
let passwprdtextfield = RegisterAlert.textFields![1]
// 使用Firebase的Auth,來新增使用者到Firebase上面
Auth.auth().createUser(withEmail: emailtextfield.text!, password: passwprdtextfield.text!,completion:{ (user,error) in
if error == nil{
Auth.auth().signIn(withEmail: emailtextfield.text!, password: passwprdtextfield.text!, completion: nil)
}else{
// 如果失敗則顯示錯誤訊息
let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(alertAction)
self.present(alert, animated: true, completion: nil)
} })
}
// 取消註冊的UIAlertAction
let CancelAction = UIAlertAction(title:"取消", style: .cancel, handler: nil)
// 新增TextField在UIAlertController內,且新增Placeholder
RegisterAlert.addTextField{(emailtextfield) in emailtextfield.placeholder = "請輸入Email"}
RegisterAlert.addTextField{(passwordtextfield) in passwordtextfield.placeholder = "請輸入password"
passwordtextfield.isSecureTextEntry = true
}
// 將兩個UIAlertAction加入UIAlertController內
RegisterAlert.addAction(RegisterAction)
RegisterAlert.addAction(cancelAction)
// 顯示
present(RegisterAlert, animated: true, completion: nil)
}
@IBAction func login (_ sender: Any){
// 使用FirebaseAuth來驗證登入是否正確
Auth.auth().signIn(withEmail: account.textfield.text!, password: password.textfield.text!, completion: {
(user,error) in
if error != nil{
let ErrorAlert = UIAlertController(title: "Error Alert", message: "Alert", preferredStyle: .alert)
let ErrorAction = UIAlertAction(title: "Error", style: .cancel, handler: nil)
ErrorAlert.addAction(ErrorAction)
self.present(ErrorAlert, animated: true, completion: nil)
}
// 當下如果登入成功,那麼就會跳轉到下個頁面
// 需要先設定跳轉的Segue跟他的Identifier名字
if user != nil{
self.performSegue(withIdentifier: "LogIning", sender: nil)
}
})
}
參考網站:
[APP開發-使用Swift] 21-2. Firebase - 新增