Swift Google 登入 Firebase 第三方登入串接👐

簡介

iOS如何使用Google登入? 常見Google登入需導入第三方登入,Firebase就是整合第三方登入的好工具,不管事FB登入IG登入或是其他第三方。

原生登入按鈕+客製化登入按鈕
安裝到實作紀錄

Google SDK 網站

pod 'GoogleSignIn'
pod 'Firebase/Analytics'
pod install

Firebase 創專案

1. 創專案

2. 添加iOS專案

3. 下載設定檔

4. 新增到Xcode

5. 複製GoogleService-Info 裡面的 REVERSED_CLIENT_ID

6. 到Info -> URL Types 新增

7. AppDelegate 新增 GIDSignInDelegate

8. AppDelegate

applicationDidFinishLaunching 初始化 GIDSignIn

func applicationDidFinishLaunching(_ application: UIApplication) {
    GIDSignIn.sharedInstance().clientID = "YOUR_CLIENT_ID"
    GIDSignIn.sharedInstance().delegate = self
}

applicationDidFinishLaunching 初始化 GIDSignIn 使用firebase

import GoogleSignIn
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate {
    var window: UIWindow?
    func applicationDidFinishLaunching(_ application: UIApplication) {
        FirebaseApp.configure()
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self
    }
}

URL回傳接收func

@available(iOS 9.0, *)
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
    return GIDSignIn.sharedInstance().handle(url)
}

登入事件

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
          withError error: Error!) {
    if let error = error {
        if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
            print("The user has not signed in before or they have since signed out.")
        } else {
            print("\(error.localizedDescription)")
        }
        return
    }
    // Perform any operations on signed in user here.
    let userId = user.userID                  // For client-side use only!
    let idToken = user.authentication.idToken // Safe to send to the server
    let fullName = user.profile.name
    let givenName = user.profile.givenName
    let familyName = user.profile.familyName
    let email = user.profile.email
    // ...
}

9. LoginViewController 新增登入按鈕+事件

GIDSignInButton 原生按鈕

import UIKit
import GoogleSignIn
class LoginViewController: UIViewController,GIDSignInDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        GIDSignIn.sharedInstance().presentingViewController = self
        GIDSignIn.sharedInstance().delegate = self
        let signInButton = GIDSignInButton()
        signInButton.frame = CGRect.init(x: 0, y: 20, width: 100, height: 25)
        self.view.addSubview(signInButton)
    }
}
Demo

– 客製化登入按鈕

import GoogleSignIn
class LoginViewController: UIViewController,GIDSignInDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        GIDSignIn.sharedInstance().presentingViewController = self
        GIDSignIn.sharedInstance().delegate = self

        let loginButton = UIButton()
        loginButton.frame = CGRect.init(x: 0, y: 20, width: 100, height: 25)
        loginButton.center.x = logoImageView.center.x
        loginButton.setTitle("登入", for: .normal)
        loginButton.setTitleColor(.darkGray, for: .normal)
        loginButton.layer.cornerRadius = loginButton.frame.height/2
        loginButton.layer.borderWidth = 1
        loginButton.layer.borderColor = UIColor.darkGray.cgColor
        loginButton.addTarget(self, action: #selector(loginButtonPress(sender:)), for: .touchUpInside)
        self.view.addSubview(loginButton)
    }

    @objc func loginButtonPress(sender:UIButton){
        GIDSignIn.sharedInstance().signIn()
    }
}
Demo

兩種登入按鈕呈現

錯誤代碼403 restructrd_client

firebase 授權問題

到firebase Authentication開啟google登入

回傳

安裝pod

pod 'Firebase/Auth'

import SDK

import FirebaseAuth

新增sign callback處理回傳至GoogleAuthProvider

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
          withError error: Error!) {
    if let error = error {
        if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
            print("The user has not signed in before or they have since signed out.")
        } else {
            print("\(error.localizedDescription)")
        }
        return
    }
    // Perform any operations on signed in user here.
    let userId = user.userID                  // For client-side use only!
    let idToken = user.authentication.idToken // Safe to send to the server
    let fullName = user.profile.name
    let givenName = user.profile.givenName //後名
    let familyName = user.profile.familyName //前名
    let email = user.profile.email
    // ...

    guard let authentication = user.authentication else { return }
    let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                   accessToken: authentication.accessToken)
    Auth.auth().signIn(with: credential) { (user, error) in
        if let error = error {
            print(error)
            return
        }
    }
}

firebase測試登入


Categorized in: