본문 바로가기

프로그래밍/iOS,macOS

[iOS] Google SignIn

pod 'Firebase/Auth'
pod 'GoogleSignIn'

import GoogleSignIn
import FirebaseAuth

 

AppDelegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {  

}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configuration()
    GIDSignIn.sharedInstance().clientID = "클라이언트ID"
    .
    .
    return true
}
func application(_ app: UIApplication, 
              open url: URL, 
               options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
    returnn GIDSignIn.sharedInstance().handle( url )
}

 

LoginViewController

class LoginViewController: UIViewController, GIDSignInDelegate {

    @IBOutput weak var button:GIDSignInButton!
    
    func viewDidLoad() {
        super.viewDidLoad()
        GIDSignIn.sharedInstance().delegate = self
        GIDSignIn.sharedInstance.presentingViewController = self
        .
        .
        // 자동 로그인
        if GIDSignIn.sharedInstance()?.hasPreviousSignIn() ?? false {
            GIDSignIn.sharedInstance()?.restorePreviousSignIn()
            
            if GIDSignIn.sharedInstance()?.currentUser.authentication.clientID != CLIENT_ID {
                GIDSignIn.sharedInstance()?.signOut()
            }
        }
    }
    
    @IBActionn func onClick(_ sender:Any) {
        GIDSignIn.sharedInstance()?.signIn()
    }
    
    
    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
        // ...
        if let error = error {
            // ...
            return
        }

        // 사용자 정보
        let userId = user.userID
        let idToken = user.authentication.idToken
        let fullName = user.profile.name
        let givenName = user.profile.givenName
        let familyName = user.profile.familyName
        let email = user.profile.email


        // firebase signin 필요시
        guard let authentication = user.authentication else { return }
        let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                       accessToken: authentication.accessToken)
        Auth.auth()?.signIn(with:creadential){ (user, error) in
            if let error = error {
            
            }
        
        }
         
         // ...
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        // Perform any operations when the user disconnects from app here.
        // ...
    }
}