[Firebase] iOS UIKit에서의 Google OAuth 로그인 연동 방법 해결 과정

2024. 3. 3. 19:20🍏/Swift

  1. Firebase 를 시작하여 프로젝트 만들기
  2. 앱에 Firebase를 추가하여 시작하기 (bundle id, nickname 등록)
    1. 구성 파일 다운로드(Google OAuth 사용자는 굳이 다운로드 안해도됨. 잠시 뒤에 credentials가 포함된 구성파일을 준다.)
    2. Upload 해도되는가에 대해서 찾아봤는데, 뭐 중요한 내용은 없다고 한다. (https://groups.google.com/g/firebase-talk/c/EEEwttbpPJU)
      그래도 저라면 안 올릴 것 같습니다.
  3. Package Dependency 추가 https://github.com/firebase/firebase-ios-sdk
  4. Appdelegate에 코드 추가
    코드 보기

    import UIKit
    import FirebaseCore
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions:
    [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    return true
    }
    }

여기까지가 Firebase 기본 설정.

아래부터 로그인 연동과정

      1. 제품 카테고리의 빌드 > Authentication > 추가 제공업체 > Google
      2. 우측키로 사용설정후 최신 구성파일 다운로드
        1. 기존 GoogleService-Info와 동일하지만 credentials가 존재하는 최신 구성파일을 받을 수 있음.
      3. TARGETS > Info > URL Types > URL Schemes에 REVERSED_CLIENT_ID의 value값 추가. 
        com.googleusercontent.apps.921929828930-bvgm52ekdqaen97lj00malabcdefghijk
        대충 이렇게 생겼음. 
      4. 인증 리디렉션 URL 처리
        코드 보기
        App delegate 같은 이름의 함수가 있을텐데 그걸 이걸로 덮어 씌우면됨.
        func application(
        _ app: UIApplication,
        open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]
        ) -> Bool {
        var handled: Bool
        handled = GIDSignIn.sharedInstance.handle(url)
        if handled {
        return true
        }
        // Handle other custom URL types.
        // If not handled by this app, return false.
        return false
        }
      5. 사용자의 로그인 상태 복원 시도
        코드 보기
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure() // 이미 추가 된줄.
        // 아래부터가 로그인 상태 복원 줄
        GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
        if error != nil || user == nil {
        // Show the app's signed-out state.
        } else {
        // Show the app's signed-in state.
        }
        }
        return true
        }
      6. https://console.cloud.google.com/ 콘솔 클라우드 구글에서 OAuth 클라이언트 ID 인증정보를 만든후 
      7. GIDClientID 등록 (info.plist)
        이미지 보기

        iOS OAuth client 클라이언트 ID 값 넣어주면됨

      8. 그럼 이제 UIKit에서 버튼 넣고 호출해주기만 하면됨
        코드 보기
        @IBAction func signIn(sender: Any) {
        GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in
        guard error == nil else { return }
        // If sign in succeeded, display the app's main content View.
        }
        }
      9. 여기까지 하면 로그인 GIDSignIn이 에러를 뱉지 않았다는 뜻이니까 로그인에 성공한 것이고, 거의 다왔음. 
        로그인 이미지 보기
        로그인 버튼
      10. 이제 해당 계정을 내 프로젝트의 firebase와 연동시켜 줘야하는 코드가 필요함
        Firebase 연동 코드
        @IBAction func signIn(sender: Any) {
        // 먼저 clientID를 검사하고 GIDConfiguration을 설정
        guard let clientID = FirebaseApp.app()?.options.clientID else { return }
        // Google SignIn configuration object 생성
        let config = GIDConfiguration(clientID: clientID)
        GIDSignIn.sharedInstance.configuration = config
        // 이제 Google Sign-In 과정을 시작합니다.
        GIDSignIn.sharedInstance.signIn(withPresenting: self) { [unowned self] result, error in
        guard error == nil else { return }
        guard let user = result?.user,
        let idToken = user.idToken?.tokenString
        else {
        return
        }
        let credential = GoogleAuthProvider.credential(withIDToken: idToken,
        accessToken: user.accessToken.tokenString)
        Auth.auth().signIn(with: credential) { result, error in
        // 여기에서 유저가 내 firebase앱에 signin함.
        guard error == nil else {
        // 인증 과정에서 에러처리 부분
        print("Firebase 인증 에러: \(error!.localizedDescription)")
        return
        }
        // 여기서 사용자가 성공적으로 로그인 처리
        print("Firebase를 통한 인증 성공")
        }
        }
        }
      11. 로그아웃
        로그아웃 코드
        let firebaseAuth = Auth.auth()
        do {
        try firebaseAuth.signOut()
        } catch let signOutError as NSError {
        print("Error signing out: %@", signOutError)
        }
      12. 버튼 키 google 버튼 양식대로 변경
        버튼 예시 코드

        https://developers.google.com/identity/sign-in/ios/reference/Enums?authuser=0

         구글에서 지원하는 googlesignin framework reference

        lazy var signInButton: GIDSignInButton = {
        let button = GIDSignInButton()
        button.style = .wide
        button.style = .standard
        button.style = .iconOnly
        button.colorScheme = .dark
        button.colorScheme = .light
        button.addTarget(self, action: #selector(signIn), for: .touchUpInside)
        return button
        }()

 

로그인에 완료되면 Firebase 의 Authentication 해당 유저가 등록이 됩니다! 끝!