[Swift] 구글 로그인 구현 (Sign in with Google)
이 포스트는 구글 로그인(Sign in with Google)을 설명하기 위한 포스팅입니다 :)
구글의 공식 문서를 기반으로 작성하였습니다.
최종 수정일 - 20. 06. 29 PM 09:50
구글 로그인 버튼 사용해보기
1. 터미널을 실행하여 프로젝트에 Podfile 을 추가해줍니다.
cd ~/[App Path] // 프로젝트의 파일 위치로 이동
pod init // Podfile 추가
2. Podfile에 구글 로그인 라이브러리를 추가해줍니다.
pod 'GoogleSignIn'
3. 터미널에서 설치합니다.
pod install // 설치
4. 구글 API 콘솔에서 사용자 인증 정보의 OAuth 2.0 클라이언트 ID를 확인합니다.
- OAuth 2.0 클라이언트 ID 는 com.googleusercontent.apps.[클라이언트 ID] 또는 [클라이언트 ID].apps.googleusercontent.com 형태를 가집니다.
5. 확인한 클라이언트 ID 를 이용해 Info.plist에 추가해줍니다.
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.[클라이언트 ID]</string>
</array>
</dict>
</array>
- Info.plist 코드로 보는 방법 : Info.plist 우클릭 - [Open As] - [Source Code]
6. AppDelegate.swift 에 추가합니다.
import GoogleSignIn
7. AppDelegate.swift 에서 application(_:didFinishLaunchingWithOptions:)에 아래 함수를 추가합니다.
// OAuth 2.0 클라이언트 ID
GIDSignIn.sharedInstance().clientID = "[클라이언트 ID].apps.googleusercontent.com"
8. SceneDelegate.swift에서 scene(_:openURLContexts:)에 아래 함수를 추가합니다.
guard let scheme = URLContexts.first?.url.scheme else { return }
if scheme.contains("com.googleusercontent.apps") {
GIDSignIn.sharedInstance().handle(URLContexts.first?.url)
}
9. 마찬가지로 ViewController.swift 에도 추가합니다.
import GoogleSignIn
10. 구글 로그인 버튼으로 사용할 뷰를 추가합니다.
// Storyboard
@IBOutlet weak var googleSignInButton: GIDSignInButton!
// Programmatically
var googleSignInButton: GIDSignInButton!
11. 구글 로그인 버튼 설정을 해줍니다.
// 구글 로그인 버튼 설정
func setGoogleSignInButton() {
GIDSignIn.sharedInstance()?.presentingViewController = self
GIDSignIn.sharedInstance().delegate = self
googleSignInButton.style = .standard // .wide .iconOnly
}
12. ViewController 에 GIDSignInDelegate를 상속합니다.
- GIDSignInUIDelegate 미사용 - 구글 로그인 마이그레이션 가이드 참조
// 연동을 시도 했을때 불러오는 메소드
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
print("The user has not signed in before or they have since signed out.")
} else {
print("\(error.localizedDescription)")
}
return
}
// 사용자 정보 가져오기
if let userId = user.userID, // For client-side use only!
let idToken = user.authentication.idToken, // Safe to send to the server
let fullName = user.profile.name,
let givenName = user.profile.givenName,
let familyName = user.profile.familyName,
let email = user.profile.email {
print("Token : \(idToken)")
print("User ID : \(userId)")
print("User Email : \(email)")
print("User Name : \((fullName))")
} else {
print("Error : User Data Not Found")
}
}
// 구글 로그인 연동 해제했을때 불러오는 메소드
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
print("Disconnect")
}
- sign(signIn:didSignInfor:withError:) 는 Google ID 연동에 성공 시 실행되는 함수입니다.
- sign(signIn:didDisconnectWith:withError:) 는 연동 해제 시 실행되는 함수입니다.
13. 앱 실행
로그인 상태를 관리하는 함수
GIDSignIn.sharedInstance()?.signIn()
GIDSignIn.sharedInstance()?.signOut()
GIDSignIn.sharedInstance()?.disconnect()
- signIn() : 로그인
- signOut() : 로그아웃
- disconnect() : 연동 해제
※ Apple 의 정책으로 모든 소셜 로그인을 사용하는 앱은 Sign in with Apple 을 함께 구현하여야 합니다.
[Swift] 애플 로그인 구현(Sign in with Apple)
이 포스트는 애플 로그인(Sign in with Apple)을 설명하기 위한 포스팅입니다 :) 애플의 공식 문서를 기반으로 작성하였으며, 애플 로그인에 대한 애플의 가이드라인은 여기에서 확인하실 수 있습니�
huisoo.tistory.com