본문 바로가기

Mobile/IOS & Swift

swift에서 firebase를 활용한 facebook로그인 예제

Swuft Login With Firebase

화면 디자인

페이스북에서 API KEY를 발급받는 내용은 생략

사용할 모듈
Podfile

pod 'Firebase/Core'
pod 'Firebase/Auth'
pod 'Firebase/Database'
pod 'Firebase/Storage'
pod 'FBSDKLoginKit' // pod
//
// .
pod 'SwiftKeychainWrapper'

뷰컨트롤러

class SignInVC: UIViewController {
//
@IBOutlet weak var emailField: FancyField!
@IBOutlet weak var pwdField: FancyField!
override func viewDidLoad() {
super.viewDidLoad()
}
//
@IBAction func facebookBtnTapped(_ sender: AnyObject) {
//
let facebookLogin = FBSDKLoginManager()
//
facebookLogin.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if error != nil {
print("error: \(error)")
} else if result?.isCancelled == true {
//
print(" ")
} else {
print(" ")
// .
let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
//firebaseAuth
self.firebaseAuth(credential)
}
}
}
//
func firebaseAuth(_ credential: FIRAuthCredential) {
// Auth
FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) in
if error != nil {
print(" ")
} else {
print(" ")
if let user = user {
self.completeSignIn(id: user.uid)
}
}
})
}
func completeSignIn(id: String) {
// KEY_UID
let keychainResult = KeychainWrapper.setString(id, forKey: KEY_UID)
//
performSegue(withIdentifier: "goToFeed", sender: nil)
}
//
@IBAction func signInTapped(_ sender: AnyObject) {
//
if let email = emailField.text, let pwd = pwdField.text {
//
FIRAuth.auth()?.signIn(withEmail: email, password: pwd, completion: { (user, error) in
if error == nil {
print("JESS: Email user authenticated with Firebase")
if let user = user {
self.completeSignIn(id: user.uid)
}
} else {
// createUser
FIRAuth.auth()?.createUser(withEmail: email, password: pwd, completion: { (user, error) in
if error != nil {
print("JESS: Unable to authenticate with Firebase using email")
} else {
print("JESS: Successfully authenticated with Firebase")
if let user = user {
self.completeSignIn(id: user.uid)
}
}
})
}
})
}
}
}

위처럼 한번 로그인을 할경우 계속해서 로그인을 하지않도록 구현을 해보자

//
override func viewDidAppear(_ animated: Bool) {
//keyChain
if let _ = KeychainWrapper.stringForKey(KEY_UID) {
print("JESS: ID found in keychain")
//
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}