본문 바로가기
iOS

[iOS] Firebase와 Google 로그인 연동하기

by thoonk: 2021. 2. 2.

Firebase를 이용해서 구글 로그인을 구현하는 방법을 기록해보겠습니다.

 

아래의 그림을 보면서 먼저 동작 원리를 살펴보자면, 구글에 로그인을 하면 구글 토큰을 받게 되고 구글 사용자임을 증명하는 구글 토큰을 이용해서 파이어베이스 로그인을 시도합니다. 그리고 성공하게 되면 파이어베이스 토큰을 얻습니다.

Firebase에서 프로젝트를 만들고 Xcode 프로젝트를 등록했다는 전제하에 시작하겠습니다. 

Podfile에 아래 두 줄을 추가하고 pod install로 설치해줍니다. 

pod 'Firebase/Auth'
pod 'GoogleSignIn'

 

그리고 프로젝트에 복사해놨던 GoogleService-Info.plist의 RESERVED_CLIENT_ID를 복사해서 아래의 그림에서 URL Schemes에 붙여줍니다. 저 부분은 Info의 목록에서 제일 아래에 있습니다.

 

그리고 AppDelegate에서 FirebaseGoogleSignIn을 import해줍니다. 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure()
    // 제대로 로그인되었는지 확인하기    
    if let user = Auth.auth().currentUser {
        print("You're sign in as \(user.uid), email: \(user.email ?? "no email")")
    }
    return true
}
// 인증 절차의 마지막에 받은 URL을 처리하기 위해서 필요한 메서드입니다.
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return GIDSignIn.sharedInstance().handle(url)
}

 

Firebase Docs에서는 AppDelegate에 로직을 더 추가하지만 저는 로그인이 성공되면 Segue 할 수 있도록 ViewController에 추가하도록 하겠습니다.

마찬가지로, ViewController에 Firebase와 GoogleSignIn을 import해줍니다. 

@IBOutlet weak var signInButton: GIDSignInButton!

버튼을 이렇게 생성해도 되지만 저는 Apple 로그인을 구현했던 StackView에 코드로 버튼을 추가하겠습니다.

아래의 코드를 모두 ViewDidLoad()에 추가해줍니다.

let googleLoginBtn = GIDSignInButton()
loginProviderStackView.addArrangedSubview(googleLoginBtn)
        
GIDSignIn.sharedInstance()?.presentingViewController = self
GIDSignIn.sharedInstance()?.delegate = self
GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID

 

Docs에서는 AppDelegate에 추가해줬던 것을 LoginVC에 추가하겠습니다. 구글에 로그인하고 사용자가 인증이 되었다면 사용자의 id토큰과 access토큰을 이용해서 파이어베이스에 로그인합니다. 

그리고 에러 없이 로그인에 성공했다면 performSegue를 이용해서 화면 전환을 시켰습니다.

// MARK: - Google Login Extension
extension LoginViewController: GIDSignInDelegate {
    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if let error = error {
            print("sigIn error: \(error.localizedDescription)")
            return
        } else {
            print("user email: \(user.profile.email ?? "no email")")
        }
        guard let auth = user.authentication else { return }
        let googleCredential = GoogleAuthProvider.credential(withIDToken: auth.idToken, accessToken: auth.accessToken)
        // 파이어베이스 로그인
        Auth.auth().signIn(with: googleCredential) { (authResult, error) in
            if let error = error {
                print("Firebase sign in error: \(error)")
                return
            } else {
                print("User is signed with Firebase&Google")
                self.performSegue(withIdentifier: "fromLoginToHome", sender: nil)
            }
        }
    }
}

 

부족한 점이 있다면 피드백해주시면 감사하겠습니다.

 

참고:

firebase.google.com/docs/auth/ios/google-signin?authuser=0

www.youtube.com/watch?v=v0HpIG2JjVs

 

'iOS' 카테고리의 다른 글

[iOS] App Bundle  (1) 2021.05.14
[iOS] FSCalendar Custom Header Swift  (2) 2021.03.10
[iOS] Apple 로그인 구현  (2) 2021.02.01
[iOS] NSOperationQueue와 GCD Queue의 차이점  (0) 2021.01.29
[iOS] URLSession API  (0) 2021.01.21

댓글