Topic/Auth

구글 아이디로 로그인 - iOS

flatlab 2024. 6. 3. 14:02

설정

파이어베이스 콘솔로 이동하여 구글 아이디로 로그인을 구현할 앱을 선택합니다.

좌측 메뉴 중 [Authentication] - [Sign-in method] - [Add new provider] - Google을 선택하고 활성화합니다.

 

프로젝트 세팅으로 돌아가 [General] - [Add app] 버튼을 클릭하여 iOS 앱을 추가합니다.

2단계에서 나타나는 창에서 GoogleService-info.plist 파일을 프로젝트 폴더에 다운로드 합니다.

앱 추가 설정을 완료합니다.

 

GoogleService-info.plist 항목 중 CLIENT_ID 값을 복사하여 프로젝트의 Info.plist에 "GIDClientID" Key로 입력합니다.

GoogleService-info.plist 항목 중 REVERSED_CLIENT_ID 값을 복사하여 [Xcode] - [Target project] - [Info] - [URL types]에 스킴 정보를 추가합니다.

 

SDK 설치

Cocoapods로 설치

# Uncomment the next line to define a global platform for your project
 platform :ios, '9.0'

target 'YOUR_PROJECT_NAME' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for YOUR_PROJECT_NAME
  
  # 구글 로그인
  pod 'FirebaseCore'
  pod 'FirebaseAuth'
  pod 'GoogleSignIn'
  pod 'GoogleSignInSwiftSupport'	# SwiftUI를 사용하는 경우

end

 

SPM으로 설치

[Xcode] 메뉴바 - [File] - [Add Package Dependencies...] 메뉴를 클릭합니다.

검색창에서 https://github.com/google/GoogleSignIn-iOS를 입력합니다.

검색된 googlesignin-ios를 선택하여 프로젝트에 추가합니다.

 

로그인 구현하기

구글 아이디로 로그인을 추가할 ViewController에서 아래 모듈을 Import 해 줍니다.

import GoogleSignIn

 

구글 아이디로 로그인 프로세서 진행 후 인증 리디렉션 URL을 처리하기 위해 AppDelegate에 GIDSignIn 클래스의 handleURL메서드를 호출합니다.

import GoogleSignIn

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        var handled: Bool

        handled = GIDSignIn.sharedInstance.handle(url)
        if handled {
            return true
        }
        
        // If not handled by this app, return false.
        return false
    }
    
}

 

ViewController와 연결되는 StoryBoard에 UIButton을 추가하고 해당 버튼의 클래스명을 GIDSignInButton으로 변경합니다.

해당 버튼에  색상과 스타일을 설정하고 클릭시 실행될 액션을 정의합니다.

import GoogleSignIn

class ViewController: UIViewController {
    
    @IBOutlet weak var googleLoginButton: GIDSignInButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        googleLoginButton.colorScheme = .light
        googleLoginButton.style = .wide
        googleLoginButton.addAction(UIAction(handler: { [weak self] _ in
            self?.googleLogin()
        }), for: .touchUpInside)
    }
    
    func googleLogin() {
        GIDSignIn.sharedInstance.restorePreviousSignIn { [self] user, error in
            if error != nil || user == nil {
              // Show the app's signed-out state.
                GIDSignIn.sharedInstance.signIn(withPresenting: self) { [self] signInResult, error in
                    guard error == nil else { return }
                        
                    guard let signInResult = signInResult else { return }

                    let user = signInResult.user

                    // If sign in succeeded, display the app's main content View.
                    showDialog(message: "구글 아이디로 로그인 인증 성공")
                }
            } else {
              // Show the app's signed-in state.
                showDialog(message: "이미 인증된 구글 아이디가 존재합니다.")
            }
        }
    }
    
}

 

로그아웃

import GoogleSignIn

class ViewController: UIViewController {
    
    @IBOutlet weak var googleLogoutButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
    }

    @IBAction func googleLogout() {
        GIDSignIn.sharedInstance.signOut()
    }
    
}

 

로그인 연결끊기

GIDSignIn.sharedInstance.disconnect를 구현하게 되면 로그인 사용자의 계정을 연결 해제하고 토큰을 취소하는 것 외에 사용자를 로그아웃시킵니다.

주의할점은 GIDSignIn.sharedInstance.disconnect를 호출하기 전에 로그인 사용자를 로그아웃 시켜서는 안됩니다.

import GoogleSignIn

class ViewController: UIViewController {
    
    @IBOutlet weak var googleUnlinkButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

    }

    @IBAction func googleUnlink() {
        GIDSignIn.sharedInstance.disconnect { [self] error in
            guard error == nil else { return }

            showDialog(message: "구글 계정과 연결을 해제하였습니다.")
        }
    }

}

 

 

참고사이트

https://developers.google.com/identity/sign-in/ios/start-integrating?hl=ko

 

iOS 및 macOS용 Google 로그인 시작하기  |  Authentication  |  Google for Developers

중요: 2024년 5월 1일부터 Apple에서는 GoogleSignIn-iOS와 같이 흔히 사용되는 SDK를 사용하는 iOS 애플리케이션의 개인 정보 보호 매니페스트 및 서명을 요구합니다. 2024년 5월 1일 전에 GoogleSignIn-iOS v7.1.0

developers.google.com

 

'Topic > Auth' 카테고리의 다른 글

카카오 로그인 - Android  (0) 2024.06.04
애플 아이디로 로그인  (0) 2024.06.03
카카오 로그인 - iOS  (1) 2024.06.03