使用 FireBase登入

Eason
彼得潘的 Swift iOS / Flutter App 開發教室
10 min readMay 31, 2023

首先第一步先安裝 CocoaPods 打開 PodFile 加入這些第三方函式。

    pod 'Firebase/Core'
pod 'Firebase/Auth'

再到 AppDelegate 裡面加幾行語法

//要記得 import 函式庫
import Firebase


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

//多加這行
FirebaseApp.configure()


return true
}

使用 FireBase 登入

        if emailAccountTextField.text == "" || passwordTextField.text == "" {
failAlert(title: "錯誤", message: "帳號或密碼不能為空")
return
}
if let emailAccount = emailAccountTextField.text,
let password = passwordTextField.text{
Auth.auth().signIn(withEmail: emailAccount, password: password) { result, error in
guard error == nil else {
print(error?.localizedDescription)
self.failAlert(title: "錯誤", message: "帳號或密碼錯誤")
return
}
if let user = result?.user{
guard let controller = self.storyboard?.instantiateViewController(withIdentifier: "\(FirebaseLoginViewController.self)") as? FirebaseLoginViewController else {return}
controller.user = user
self.navigationController?.pushViewController(controller, animated: true)
}
print("success")
}
}

(登入)作品:

註冊

        if emailAccountTextField.text == "" {
failAlert(title: "錯誤", message: "信箱不得為空")
}


if let email = emailAccountTextField.text,
let password = passwordTextField.text,
let name = nameTextField.text {
Auth.auth().createUser(withEmail: email, password: password) { result, error in

guard let user = result?.user,
error == nil else {
print(error?.localizedDescription)
return
}
let profileChangeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
profileChangeRequest?.displayName = name
profileChangeRequest?.commitChanges(completion: { error in
guard error == nil else {
print(error?.localizedDescription)
return
}
})
print(user.email, user.uid,user.displayName)
DispatchQueue.main.async {
self.navigationController?.popViewController(animated: true)
}
}
}

(註冊)作品:

利用 Google 登入 需要加一些程式碼

import GoogleSignIn

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

ApplicationDelegate.shared.application(app, open: url, options: options)

return GIDSignIn.sharedInstance.handle(url)
}

在Controller 設計一個 func

    @objc func googleLogin(_ sender: Any) {
//透過 guard let 取得clientID
//指派 config 取得上面的clientID
//透過GIDSignIn嘗試授權跳出頁面協助登入
//登入成功跳轉頁面

guard let clientID = FirebaseApp.app()?.options.clientID else { return }
let config = GIDConfiguration(clientID: clientID)
GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in
if let user = user ,
let idToken = user.authentication.idToken {
let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: user.authentication.accessToken)
Auth.auth().signIn(with: credential) { result, error in
if let user = result?.user{
guard let controller = storyboard?.instantiateViewController(withIdentifier: "\(FirebaseLoginViewController.self)") as? FirebaseLoginViewController else {return}
controller.user = user
navigationController?.pushViewController(controller, animated: true)
}

}

}


}
}

(Google)登入:

使用 FaceBook 登入

        let manager = LoginManager()
manager.logIn(permissions: [.publicProfile], viewController: self) { result in
if case LoginResult.success(granted: _, declined: _, token: let token) = result {
print("fb login ok")

let credential = FacebookAuthProvider.credential(withAccessToken: token!.tokenString)
Auth.auth().signIn(with: credential) { [weak self] result, error in
guard let self else { return }
guard error == nil else {
print(error?.localizedDescription)
return
}
if let user = result?.user {

guard let controller = self.storyboard?.instantiateViewController(withIdentifier: "\(FirebaseLoginViewController.self)") as? FirebaseLoginViewController else {return}
controller.user = user

self.navigationController?.pushViewController(controller, animated: true)
}
print("login ok")
}

} else {
print("login fail")
}
}

(FaceBook)作品:

參考:

GitHub:

--

--