Swift: Firebase Chat App Part 7 - Google Sign In & Sign Out (Real-time) - Xcode 11 - 2020
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
ApplicationDelegate.shared.application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplication.OpenURLOptionsKey.annotation]
)
return GIDSignIn.sharedInstance.handle(url)
}
AppDelegate
내 url에 따라 값을 리턴하는 함수 private let googleLoginButton: GIDSignInButton = {
let button = GIDSignInButton()
return button
}()
@objc private func googleSignIn() {
guard let clientID = FirebaseApp.app()?.options.clientID else { return }
let config = GIDConfiguration(clientID: clientID)
GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [unowned self] user, error in
if let error = error {
print(error.localizedDescription)
return
}
guard
let authentication = user?.authentication,
let idToken = authentication.idToken else { return }
guard
let email = user?.profile?.email,
let firstName = user?.profile?.givenName,
let lastName = user?.profile?.familyName else { return }
DatabaseManager.shared.userExists(with: email, at: Platform.Google) { exists in
if !exists {
DatabaseManager.shared.insertUser(with: ChatAppUser(firstName: firstName, lastName: lastName, emailAddress: email, platform: .Google))
}
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: authentication.accessToken)
FirebaseAuth.Auth.auth().signIn(with: credential) { [weak self] result, error in
guard let self = self else { return }
guard
result != nil,
error == nil else {
if let error = error {
print("Facebook credential login failed, MFA may be needed - \(error)")
}
return
}
print("Successfully logged user in")
NotificationCenter.default.post(name: .didSignInNotification, object: nil)
}
}
}
GIDSignIn.sharedInstance
의 signIn
메소드를 통해 클라이언트 아이디 전달 및 인증 가능FirebaseAuth.Auth.auth().signIn(with: AuthCredentail)
로 로그인 private var signInObserver: NSObjectProtocol?
private func setObserver() {
signInObserver = NotificationCenter.default.addObserver(forName: Notification.Name.didSignInNotification, object: nil, queue: .main, using: { [weak self] _ in
guard let self = self else { return }
self.navigationController?.dismiss(animated: true, completion: nil)
})
}
deinit {
if let observer = signInObserver {
NotificationCenter.default.removeObserver(observer)
print("Observer removed")
}
}
deinit
에서 해당 옵저버를 중앙 센터에서 해제