본문 바로가기

EXPERIENCE/iOS

[Xcode/iOS] Swift 구글(Google)로그인 스토리보드(StoryBoard)로 구현하고 정보 가져오기

728x90
728x90

 

 

 

 

728x90

 

 

 

 

 

구글, 애플, 카카오, 네이버 각종 소셜로그인을 모두 구현하여 포스팅 해볼 예정이다!

오늘은 첫번째로 구글 로그인을 준비했으며 추후 SwiftUI로 구현한 내용도 업로드할 예정이다 :)

 

 

 

 

결과화면

 

 

 

 

Document
 

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

이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 의견 보내기 iOS 및 macOS용 Google 로그인 시작하기 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류

developers.google.com

 

 

 

 

 

Github
 

GitHub - sohay19/Social-Login: Social Login

Social Login. Contribute to sohay19/Social-Login development by creating an account on GitHub.

github.com

 

 

 

 

 

SDK 설치

 

 

  • CocoaPods 설치 방법
 

[Xcode/iOS] CocoaPods 설치 및 Podfile 명령어 정리

Swift Package Manager도 존재하지만 역시 cocoaPods이 버전 문제만 안나면 편한 것 같다 ㅎㅎ 간단하게 설치 및 사용법 그리고 명령어를 다시 보기위해 정리해두려한다. CocoaPods 설치 sudo gem install cocoapods

s-o-h-a.tistory.com

 

 

  • GoogleSignIn 설치

pod 'GoogleSignIn'

 

 

 

 

OAuth 클라이언트 ID 만들기

 

  • Firebase 프로젝트 만들기
 

로그인 - Google 계정

이메일 또는 휴대전화

accounts.google.com

1. Firebase Console에 접속한다
2. 새로운 프로젝트를 추가한다
(기존 프로젝트 이용 시 건너뛰기)

 

 

  • OAuth 클라이언트 ID 만들기

1. 페이지에 접속한다
2. "OAuth 클라이언트 ID 만들기"를 클릭한다
(기존 프로젝트 이용 시 하단의 "기존 OAuth 클라이언트 ID 가져오기"선택)

 

 

 

3. 만든 프로젝트를 선택한다
4. Xcode 프로젝트의 Bundle ID를 입력한다
5. 완료

 

 

 

 

OAuth ID 확인 (ClientID)

 

 

 

1. 이전 페이지에서 이번에는 하단의 "기존 OAuth 클라이언트 ID 가져오기" 버튼 클릭
2. 설정했던 프로젝트 선택
3. "OAuth client' 클릭
4. "클라이언트 ID"와 "iOS URL 스키마" 두가지 정보를 기억해둔다

 

 

 

 

info.plist 수정

1. 프로젝트 폴더 내의 Info.plist를 찾아 선택한다
2. 행을 추가하여 "GIDClientID"를 Key값에 입력하고 Value 값에는 앞서 기억해둔 "클라이언트ID"를 입력한다

 

 

 

 

URL Scheme 추가

1. 프로젝트를 클릭한 후, TARGETS에서 해당하는 타겟을 선택한다
2. Info 메뉴를 클릭하여 하단의 URL Types을 연다
3. "+" 버튼을 눌러 항목을 추가한 후 URL Schemes에 위에서 확인한 "iOS URL 스키마"를 입력해준다

 

 

 

 

구현하기

 

  • AppDelegate.swift
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
    return GIDSignIn.sharedInstance.handle(url)
}
"인증 리디렉션 URL 처리"를 위해 추가해준다

 

 

  • UserData.swift
struct UserData {
    let profile:UIImage
    let name:String
    let email:String
}
유저 데이터 저장을 위한 구조체

 

 

  • ViewController.swift (Main)
class ViewController: UIViewController {
    @IBOutlet weak var btnGoogleLogin: GIDSignInButton!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 버튼 스타일 설정
        btnGoogleLogin.colorScheme = .light
        btnGoogleLogin.style = .wide
        
        // 기존에 로그인한 경우 바로 페이지 이동
        checkState()
    }
}
- GIDSignInButton : 스토리보드에 View를 추가한 후 class를 "GIDSignInButton"로 지정하면 구글에서 제공하는 로그인 버튼을 사용할 수 있다

 

//MARK: - Google Login
extension ViewController {
    // 기존 로그인 상태 확인
    func checkState() {
        GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
            if error != nil || user == nil {
                // 비로그인 상태
                print("Not Sign In")
            } else {
                // 로그인 상태
                guard let user = user else { return }
                guard let profile = user.profile else { return }
                // 유저 데이터 로드
                self.loadUserData(profile)
            }
        }
    }
    // 구글 로그인
    func googleLogin() {
        GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in
            guard error == nil else {
                // 로그인 실패 시
                let popup = UIAlertController(title: "로그인 실패", message: "다시 로그인해주세요", preferredStyle: .alert)
                let action = UIAlertAction(title: "확인", style: .default)
                popup.addAction(action)
                self.present(popup, animated: true)
                return
            }
            // 로그인 성공 시
            guard let user = signInResult?.user else { return }
            guard let profile = user.profile else { return }
            // 유저 데이터 로드
            self.loadUserData(profile)
        }
    }
    // 유저 데이터 전달
    func loadUserData(_ profile:GIDProfileData) {
        let emailAddress = profile.email
        let fullName = profile.name
        let profilePicUrl = profile.imageURL(withDimension: 180)
        
        // 이미지 다운로드
        if let profilePicUrl = profilePicUrl {
            DispatchQueue.global().async {
                if let data = try? Data(contentsOf: profilePicUrl) {
                    if let image = UIImage(data: data) {
                        // UI는 main thread에서만 접근가능
                        DispatchQueue.main.async {
                            let data = UserData(profile: image, name: fullName, email: emailAddress)
                            self.moveMyPage(data)
                        }
                    }
                }
            }
        }
    }
    // 마이페이지 이동
    func moveMyPage(_ data:UserData) {
        let board = UIStoryboard(name: "MyPage", bundle: nil)
        guard let nextVC = board.instantiateViewController(withIdentifier: "MyPage") as? MyPageViewController else { return }
        nextVC.userData = data
        nextVC.modalTransitionStyle = .coverVertical
        nextVC.modalPresentationStyle = .overFullScreen
        self.present(nextVC, animated: true)
    }
}

//MARK: - Event
extension ViewController {
    @IBAction func clickGoogleLogin(_ sender:Any) {
        googleLogin()
    }
}
- googleLogin() : 구글 로그인을 진행하는 함수
- checkState() : 기존 로그인 상태를 체크하여 자동 로그인을 진행해주는 함수
- loadUserData() : 로그인 결과에 따라 유저 데이터를 저장해주는 함수
- moveMyPage() : 마이페이지로 이동하는 함수

 

 

  • MyPageViewController.swift
class MyPageViewController : UIViewController {
    @IBOutlet weak var imgProfile:UIImageView!
    @IBOutlet weak var labelEmail:UILabel!
    @IBOutlet weak var labelName:UILabel!
    
    var userData:UserData?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 로그인 확인 후 프로필 로드
        loadProfile()
    }
}
유저의 프로필 사진, 이름, 이메일을 띄우는 마이페이지
메인페이지에서 로그인 후 유저데이터를 전달 받음

 

extension MyPageViewController {
    // 프로필 가져오기
    func loadProfile() {
        guard let userData = userData else { return }
        imgProfile.image = userData.profile
        labelName.text = userData.name
        labelEmail.text = userData.email
    }
    // 로그아웃
    func logout() {
        GIDSignIn.sharedInstance.signOut()
        
        // 메인 화면으로 이동
        let board = UIStoryboard(name: "Main", bundle: nil)
        guard let nextVC = board.instantiateViewController(withIdentifier: "Main") as? ViewController else { return }
        nextVC.modalTransitionStyle = .coverVertical
        nextVC.modalPresentationStyle = .overFullScreen
        self.present(nextVC, animated: true)
    }
}

//MARK: - Event
extension MyPageViewController {
    // 로그아웃 버튼 클릭
    @IBAction func clickLogout(_ sender:Any) {
        logout()
    }
}
- loadProfile() : 유저데이터를 이용해 정보를 띄운다
- logout() : 로그아웃을 진행하고 메인페이지로 돌아간다

 

 

 

 

 

OAuth 동의화면 앱 이름 및 정보 변경
 

구글 로그인(Google Login) OAuth 동의화면 앱 이름 및 정보 변경

결과화면 구글 연동 로그인을 진행하다보면 해당 빨간 박스 부분에 내 앱 이름이 아니라 project~라고 뜰 때가 있다. 이때 아래 메뉴에서 해당 내용을 변경할 수 있다. 동의화면 앱 이름 변경 로그

s-o-h-a.tistory.com

 

 

 

 

 

추후 Firebase 인증까지 사용하면 좀 더 코드가 길고 귀찮아졌던 것 같은데...

우선 로그인만 진행하면 사전 세팅이 많을 뿐 생각보다 간단하다!

다음 포스팅은 완전 같은 내용을 SwiftUI로 진행하고자 한다 :)

 

 

 

 

 

 

 

 

 

728x90
728x90