문제상황
Firebase를 이용하여 Google 로그인 버튼을 문서를 보고 구현하고 미흡한 부분이 없는지 이전에 봐둔 예제를 보고 참고하려고 했다. 2022년 예제인데도 그새 방식이 바뀐 모양인지 Delegate를 이용하여 AppDelegate에서 이뤄지는 작업이 대폭 축소되고 로직을 구현하는 ViewController의 역할이 증가하였다.
지금은 아래의 코드가 AppDelegate에서 하는 역할의 전부다.
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FirebaseApp.configure()
...
return true
}
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance.handle(url)
}
해결
먼저, GoogleSignIn을 import 한다.
import GoogleSignIn
다음으로 버튼을 선언하고 UI를 잡아준다.
private let googleLoginButton = GIDSignInButton()
target 설정으로 버튼을 통해 발생하는 이벤트를 정의하자.
clientID를 받고 config 설정을 해준다. 이를 이용하여 user의 idToken, 프로필 정보를 추출할 수 있다.
GoogleAuthProvider에서 credential을 받는 것이 핵심으로 이를 다시 Firebase에 넣어줌으로써 로그인을 구현할 수 있다.
@objc
private func googleSignIn() {
guard let clientID = FirebaseApp.app()?.options.clientID else { return }
let config = GIDConfiguration(clientID: clientID)
GIDSignIn.sharedInstance.configuration = config
GIDSignIn.sharedInstance.signIn(withPresenting: self) { [unowned self] result, error in
if let error = error {
print(error.localizedDescription)
return
}
guard
let user = result?.user,
let idToken = user.idToken?.tokenString else { return }
let credential = GoogleAuthProvider.credential(withIDToken: idToken,
accessToken: user.accessToken.tokenString)
FirebaseAuth.Auth.auth().signIn(with: credential, completion: { [weak self] result, error in
guard
result != nil,
error == nil else {
if let error = error {
print("Google credential login failed")
}
return
}
print("Successfully logged user in")
})
}
}
위 코드는 공식 문서에서도 안내하는 기초적인 코드다. 정상적인 로그인 경험이라면 유저의 정보를 추출함과 동시에 Navigation나 dismiss를 시행하는 게 보편적이겠다. 내 경우 코드가 굉장히 더럽게 됐기 때문에 위의 코드만 올린다.
'Swift > etc' 카테고리의 다른 글
| [Tuist] 새로 생성한 Sources, Resources 폴더가 안 보일 때 (0) | 2023.04.01 |
|---|---|
| [Tuist] 삭제한 dependency가 여전히 남아있을때 (0) | 2023.03.31 |
| [Firebase] Database lives in a different region 에러 (0) | 2023.03.21 |
| [Swift] Kingfisher와 SDWebImage (0) | 2023.03.19 |
| [RxSwift] debounce 그리고 throttle (덤으로 distinctUntilChanged) (0) | 2023.03.19 |