Swift: Firebase Chat App Part 6 - Facebook Login & Log Out (Real-time) - Xcode 11 - 2020
func loginButton(_ loginButton: FBLoginButton, didCompleteWith result: LoginManagerLoginResult?, error: Error?) {
guard let token = result?.token?.tokenString else {
print("User failed to log in with facebook")
return
}
let facebookRequest = FBSDKLoginKit.GraphRequest(graphPath: "me",
parameters: ["fields" : "email, name"],
tokenString: token,
version: nil, httpMethod: .get)
// login and get token to get user info
facebookRequest.start { _, result, error in
guard
let result = result as? [String : Any],
error == nil else {
print("Failed to make facebook graph request")
return
}
guard
let userName = result["name"] as? String,
let email = result["email"] as? String else {
print("Failed to get email and name from fb result")
return
}
let nameComponents = userName.components(separatedBy: " ")
guard nameComponents.count == 2 else {
return
}
let firstName = nameComponents[0]
let lastName = nameComponents[1]
// from facebook data to firebase database
DatabaseManager.shared.userExists(with: email) { exists in
if !exists {
DatabaseManager.shared.insertUser(with: ChatAppUser(firstName: firstName, lastName: lastName, emailAddress: email))
}
}
// log in and navigate to main view
let credential = FacebookAuthProvider.credential(withAccessToken: token)
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")
self.navigationController?.dismiss(animated: true, completion: nil)
}
}
}
페이스북뿐만 아니라 구글, 애플 등 SNS 간편 로그인 기능은 로그인이 필요한 앱 서비스를 제공하는 데 있어 필수적이다. 파이어베이스와 함께 사용하는 방법 및 간편 로그인 자체의 API 사용법을 확인하자.