iT邦幫忙

2023 iThome 鐵人賽

DAY 13
0
Mobile Development

App從開發到上架系列 第 13

Day14: iOS 開發:畫面功能(會員) - 透過第三方來登入

  • 分享至 

  • xImage
  •  

今天是實作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!!!!!!!")
        }
    }
}



上一篇
Day13: iOS 開發:畫面功能(會員) - 基本註冊
下一篇
Day15: iOS 開發:畫面建構(最新消息) - NewsViewController
系列文
App從開發到上架30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言