본문 바로가기

IOS

Swift - Google Login

Google Login 연동 진행하다가 규격서가 바껴서 그런지 다른 블로그에서 내용을 찾지못해 직접 작성했습니다.

무엇보다 가이드는 공식이 최고...


1. OAuth 2.0 추가

??? 왜 Xcode 말고 이거부터 하지 라고 생각할수 있는데, Xcode 관련한 내용은 한꺼번에 정리하기 위해 먼저 작성했습니다.

실제 연동할땐 순서 상관 없습니다.

https://console.cloud.google.com/ 

 

Google 클라우드 플랫폼

로그인 Google 클라우드 플랫폼으로 이동

accounts.google.com

 

1-1. 클라우드 플랫폼에서 신규 프로젝트를 생성 합니다.

1-2. 생성후 API 및 서비스 -> 사용자 인증정보 -> 사용자 정보 인증 만들기 -> OAuth 클라이언트 ID 를 클릭해 생성 해줍니다.

  * 생성 완료후 클라이언트 ID, iOS URL 스키마 는 꼭 복사 해주세요


2.  Xcode 설정

2-1. 신규 프로젝트는 생성했다는 가정하에 진행 합니다.

pod 혹은 SPM 으로 Google Login 라이브러리를 설치 해줍니다. 필자는 SPM 으로 진행 합니다. (GoogleSignIn, GoogleSignInSwift) 둘다 설치 해줍니다.

https://github.com/google/GoogleSignIn-iOS

 

GitHub - google/GoogleSignIn-iOS: Enables iOS and macOS apps to sign in with Google.

Enables iOS and macOS apps to sign in with Google. - GitHub - google/GoogleSignIn-iOS: Enables iOS and macOS apps to sign in with Google.

github.com

 

2-2. plist.info 에 해당 내용을 추가 합니다.

* 1-2 에서 복사한 내용을 추가합니다.

<key>GIDClientID</key>
<string>클라이언트 ID(숫자로 시작)</string>
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>iOS URL 스키마 (com 으로 시작)</string>
    </array>
  </dict>
</array>

신규 생성한 프로젝트는 plist.info 가 없어졌을수도 있습니다. 그러면 Project -> Info -> Custom iOS Target Properties 에 App Transport Security Settings 내용 추가해주면 신규로 plist.info 가 생깁니다. 거기에다가 추가 해줘도 괜찮습니다.

 

2-3. @main 파일에 해당 내용 추가

import SwiftUI
import GoogleSignIn

@main
struct GoogleLoginExampleApp: App {
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear {
                    GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
                        // Check if `user` exists; otherwise, do something with `error`
                    }
                }
                .onOpenURL { url in
                    GIDSignIn.sharedInstance.handle(url)
               }
        }
    }
}

onAppear 와 onOpenURL 상에 해당 내용 추가해줍니다. 상세 내용과 SwiftUI 가 아니라 UiKit 환경 내용은 Google 연동 규격서를 확인합니다.

 

2-4. ContentView 내용 추가

import SwiftUI
import GoogleSignInSwift
import GoogleSignIn

struct ContentView: View {
    var body: some View {
        VStack {
            GoogleSignInButton(action: handleSignInButton)
        }
        .padding()
    }
    
    func handleSignInButton() {
        
        guard let presentingViewController = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first?.rootViewController else {return}
        
        GIDSignIn.sharedInstance.signIn(
        withPresenting: presentingViewController) { signInResult, error in
          guard let result = signInResult else {
            // Inspect error
            return
          }
        }
    }
}

버튼은 따로 구글에서 제공하는 버튼을 이용했고, 애플과 다르게 버튼을 따로 제작해도 괜찮은거 같습니다.

로그인 완료에 대한 데이터는 result.user (GIDGoogleUser) 상에 담겨져 있습니다 (사용자 이름, 이메일, 사진 등등)


마치며

연동 자체가 어려운 부분은 아니라, 공식 문서 통하면 연동 하는데 문제는 없어 보입니다.

다만 직접 연동 하다가 개인적으로 부족한 내용이 있어서 추가 했습니다.

회사일이 바빠 요즘 포스팅 하기 어렵네요 ㅠㅠ 자주 할수 있도록 노력 하겠습니다.

 

참고

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

 

프로필 정보 가져오기  |  Authentication  |  Google for Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 의견 보내기 프로필 정보 가져오기 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 사용

developers.google.com