본문 바로가기
iOS/UIKit

[Swift/iOS] 구글 로그인 구현하기!

by 최지철 2023. 2. 28.
728x90
반응형

1.Pod에 구글로그인 sdk를 추가해줍니다.

pod 'GoogleSignIn'

 

2. https://cloud.google.com/?hl=ko 

구글 클라우드 플랫폼 콘솔로 들어가서

클라이어튼 ID 만들기를 클릭

저희는 당연히 iOS를 선택해야겠죠?

개인적으로 PLIST를 다운로드해서 따로 클라이언트 ID를 관리하는게 좋습니다~(추천임 굳이 안해도 NO matter~)

3.  URL Types에서 추가해서 역순으로 되어있는 구글클라이언트ID가 있습니다. (다운받으신 PLIST)

 

 

4. AppDelegate에 있는 didFinsihLaunching 함수에 아래 코드를 추가 해주십쇼

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

        

        GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in

          if error != nil || user == nil {

            // 로그인 상태

          } else {

            // 로그아웃 상태

          }

        }

        return true

    }

 

요 아래 함수도 추가해주십쇼

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

        if GIDSignIn.sharedInstance.handle(url){

            return true

        }

}

 

5. iOS 13이상 부터는 SceneDelegate에 아래 함수를 추가해주어야합니다.   (이하는 위에 AppDelegate 두번째함수를 추가해야합니다.)

 

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

        if let url = URLContexts.first?.url {

             if (AuthApi.isKakaoTalkLoginUrl(url)) {

                 _ = AuthController.handleOpenUrl(url: url)

             }else {

                 GIDSignIn.sharedInstance.handle(url)

             }

         }

    }

 

6.뷰 컨트롤러에서 코드 추가합니다.

import GoogleSignIn //당연히 임포트 해야겟죠?

 

func googleLoginPase() { // 로그인 유저 정보를 들고오는 함수입니다~

        GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in

            guard error == nil else { return }

            guard let signInResult = signInResult else { return }

            

            let user = signInResult.user

            

            let emailAddress = user.profile?.email

            

            let fullName = user.profile?.name

            let givenName = user.profile?.givenName

            let familyName = user.profile?.familyName

            

            let profilePicUrl = user.profile?.imageURL(withDimension: 320)

            print(emailAddress as Any)

            print(fullName as Any)

            print(givenName as Any)

            print(familyName as Any)

            print(profilePicUrl as Any)

 

        }

    }

 

7. 이벤트를 발생시키고 싶은 함수에 아래 코드를 추가합니다.

 

    @IBAction func googleLoginBtn(_ sender: Any) {

// 예제이니 이 함수 아래에있는 코드를 사용하세요~ 다들 아시죠? 혹시나해서요 ㅎㅎ

        GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in

            guard error == nil else { return }

            self.googleLoginPase()

          }

    }

잘 되네욤~ㅎㅎ

 

 

 

 

 

 

728x90
반응형