简体   繁体   中英

Google and Facebook Firebase login authentication using swift 3 in ios

I want to implement both Logins using google and log in using Facebook in a view using firebase auth

AppDelegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
        return true
    }

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        let handled =  FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication,annotation: annotation)
        return handled
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return GIDSignIn.sharedInstance().handle(url,
                                                 sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,annotation: [:])
    }
}

ViewController.swift

class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        GIDSignIn.sharedInstance().uiDelegate = self
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self 
    }

    @IBAction func GSignInPressed(_ sender: Any) {
        print("GsignIn pressed")
        GIDSignIn.sharedInstance().signIn()
    }

    @IBAction func fbPressed(_ sender: Any) {

        let facebookLogin = FBSDKLoginManager()

        facebookLogin.logIn(withReadPermissions: ["email", "public_profile"], from: self) { (result, error) in
            if error != nil {
                print("uhhhh! unable to connect with facebook")
            } else if result?.isCancelled == true {
                print("Uhhh! User cancelled FB auth")
            } else {
                print("Uhhh! Sucessfully authenticated with FB")
                let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
                self.firebaseAuth(credential)
            }
        }
    }

    func firebaseAuth(_ credential: AuthCredential) {

        Auth.auth().signIn(with: credential) { (user, error) in
            if error != nil {
                // ...
                print("Error in credentials")
                print(error!)
                return
            }
            // User is signed in
            // ...
            let email = user?.email
            print(email!)
        }
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if error != nil {
            print("error in google sign in")
            return
        }
        guard let authentication = user.authentication else { return }
        let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,accessToken: authentication.accessToken)
        self.firebaseAuth(credential)
    }
}
 //MARK: - Handle URL for FB and Google Sign -
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

    //handle the URL that your application receives at the end of the authentication process -
    var flag: Bool = false
    // handle Facebook url scheme
    if let wasHandled:Bool = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) {
        flag = wasHandled
    }
    // handle Google url scheme
    if let googlePlusFlag: Bool = GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication!, annotation: annotation) {
        flag = googlePlusFlag
    }
    return flag
}

Try with this in AppDelegate

FIREBASE LOGIN WITH FACEBOOK & GOOGLE AUTH STEP BY STEP FOR SWIFT 4.1 VERSION :-

  1. Set up FireBase + FB + Google Environment inside your project(ignore if already set) :-

    Fire Base Set Up:- https://firebase.google.com/docs/ios/setup

    Facebook Set Up :- https://developers.facebook.com/docs/facebook-login/ios

    Google Set Up :- https://developers.google.com/identity/sign-in/ios/start-integrating

  2. Go in your project Appdelegate.swift file and set up related to FIREBASE + FB + GOOGLE :-

import UIKit import Firebase import FirebaseAuth import FacebookLogin import FBSDKLoginKit import FacebookCore import GoogleSignIn

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FirebaseApp.configure()
    //google sign in
    GIDSignIn.sharedInstance().clientID = "Your Google Client ID"
    FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
    return true
}


func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
 }
}

3.Implement your FB+Google+Logout Actions from your UIViewController :-

import UIKit import FirebaseAuth import FacebookLogin import FBSDKLoginKit import FacebookCore import GoogleSignIn

class FLoginVc: UIViewController,GIDSignInDelegate,GIDSignInUIDelegate {
  override func viewDidLoad() {
    super.viewDidLoad()
   }

    @objc func btnActionTaped(btn:UIButton){
    switch btn.tag {
    case 0:
        print("manual")
        Auth.auth().signIn(withEmail: (txtEmail.text ?? ""), password: (txtPass.text ?? "")) { (result, error) in
            if let _eror = error{
                print(_eror.localizedDescription)
            }else{
                if let _res = result{
                    print(_res)
                }
            }
        }  
    case 1:
        print("facebook loginbutton clicked")
        getFacebookUserInfo()
    case 2:
        print("google login button clicked")
        GIDSignIn.sharedInstance().delegate=self
        GIDSignIn.sharedInstance().uiDelegate=self
        GIDSignIn.sharedInstance().signIn()
   case 3:
        print("logout button clicked")
        do {
            try Auth.auth().signOut()
            print("user signed out")
        } catch let err {
            print(err)
        }
    default:
        break
    }
  }
  //MARK:- FACEBOOK LOGIN METHOD
  func getFacebookUserInfo(){
     let loginManager = LoginManager()
    loginManager.logIn(readPermissions: [ReadPermission.publicProfile,ReadPermission.email], viewController: self) { (result) in
        switch result{
        case .cancelled:
            print("Cancel button click")
        case .success:
            let facebookCredential:AuthCredential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
            self.loginFireBaseWithCredential(credential: facebookCredential)
        default:
            print("??")
        }
    }
  }

  //MARK:- GOOGLE SIGN IN DELEGATE
  func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) {
  }
  func sign(_ signIn: GIDSignIn!,
          present viewController: UIViewController!) {
    self.present(viewController, animated: true, completion: nil)
  }
  func sign(_ signIn: GIDSignIn!,
          dismiss viewController: UIViewController!) {
    self.dismiss(animated: true, completion: nil)
  }
      public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
                   withError error: Error!) {
    if (error == nil) {
        guard let authentication = user.authentication else { return }
       let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                      accessToken: authentication.accessToken)
        self.loginFireBaseWithCredential(credential: credential)
    } else {
        print("\(error.localizedDescription)")
    }
}
  //MARK:- FireBase Auth credential login
  func loginFireBaseWithCredential(credential:AuthCredential){
    Auth.auth().signInAndRetrieveData(with: credential) {(result, error) in
        if error != nil {
            print("\(credential) Authentification Fail")
        } else {
            //firebase user loggedin successfully through google.
            if let user = result?.user{
                print(user.email)
                print(user.displayName)
            }
        }
    }
   }
   override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }


}

NOTE:- Always Logout before login with another social option (if logged in with facebook logout first and then login with another and use unique email address)

HAPPY CODING!!!;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM