今天是實作Google登入,程式碼如下:
//
// MemberShipViewController.swift
// FoodDemo
//
// Created by Wang Allen on 2023/9/19.
//
import UIKit
import FirebaseAuth
import Firebase
import GoogleSignIn
class MemberShipViewController: BaseViewController {
// MARK: - IBOutlet
@IBOutlet weak var btnLogin: CustomButton!
@IBOutlet weak var btnGoogleLogin: CustomButton!
@IBOutlet weak var txfAccount: UITextField!
@IBOutlet weak var txfPassword: UITextField!
@IBOutlet weak var imgvMembericon: UIImageView!
@IBOutlet weak var lbMemberShipName: UILabel!
// MARK: - Variables
var b_isLogin: Bool = false
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
print("you enter MemberShipViewController!")
txfAccount.attributedPlaceholder = NSAttributedString(string: "Please Enter your Account....",attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange])
txfPassword.attributedPlaceholder = NSAttributedString(string: "Please Enter your Password....",attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange])
txfPassword.isSecureTextEntry = true
let temp = imgvMembericon.image?.withRenderingMode(.alwaysTemplate)
imgvMembericon.image = temp
imgvMembericon.tintColor = .systemOrange
self.lbMemberShipName.text = "Please Login"
}
@IBAction func btnGoogleTapped(_ sender: Any) {
self.signInWithGoogle()
}
@IBAction func btnLoginTapped(_ sender: Any) {
if b_isLogin == true {
do {
try Auth.auth().signOut()
print("Logout successed!")
self.txfAccount.text = ""
self.txfPassword.text = ""
} catch let error as NSError {
print("\(String(describing: error.localizedDescription))")
}
} else {
Auth.auth().createUser(withEmail: txfAccount.text!, password: txfPassword.text!) { result, error in
guard let user = result?.user,
error == nil else {
print(error?.localizedDescription as Any)
return
}
print(user.email as Any, user.uid)
self.lbMemberShipName.text = "Welcome !"
self.btnLogin.setTitle("Logout", for: .normal)
self.b_isLogin = true
}
}
}
// 登入帳號
func signInWithGoogle() {
guard let clientID = FirebaseApp.app()?.options.clientID else { return }
let config = GIDConfiguration(clientID: clientID) // 創建 Google Sign In Config 物件
GIDSignIn.sharedInstance.signIn(withPresenting: self) { [unowned self] result, error in
guard error == nil else {
print("\(String(describing: error!.localizedDescription))")
return
}
guard let user = result?.user, let idToken = user.idToken?.tokenString else { return }
let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: user.accessToken.tokenString)
self.firebaseSignInWithGoogle(credential: credential)
}
}
// 將上面從 Google 登入後的資訊,告訴 Firebase
func firebaseSignInWithGoogle(credential: AuthCredential) {
Auth.auth().signIn(with: credential) { authResult, error in
guard error == nil else {
print("\(String(describing: error!.localizedDescription))")
return
}
print("success!!!!!!!")
}
}
}