Google and Facebook Firebase Auth using swift 3

2019-04-15 18:14发布

My google sign is not prompting users to allow permissions in their profile while facebook is prompting. Why?

I am implementing my google login in view controller not in app delegate like in the guide. I'm not sure what i did is correct. I've been trying to implement this for hours.

Here's my code:

apple delegate.swift

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FIRApp.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)
        GIDSignIn.sharedInstance().handle(url,
                                          sourceApplication: sourceApplication,
                                          annotation: annotation)

        return handled
    }


    // my viewcontroller.swift

    class LoginViewController: UIViewController, FBSDKLoginButtonDelegate, NVActivityIndicatorViewable, GIDSignInUIDelegate, GIDSignInDelegate {

        @IBOutlet weak var fbLogin: FBSDKLoginButton!
        var databaseRef: FIRDatabaseReference!
        var size = CGSize(width: 30, height: 30)

        override func viewDidLoad() {
            super.viewDidLoad()

            GIDSignIn.sharedInstance().uiDelegate = self
            GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
            GIDSignIn.sharedInstance().delegate = self


            NVActivityIndicatorView.DEFAULT_TYPE = .ballTrianglePath
            NVActivityIndicatorView.DEFAULT_BLOCKER_DISPLAY_TIME_THRESHOLD = 2

            FIRAuth.auth()?.addStateDidChangeListener() { (auth, user) in
                if user != nil{
                    self.performSegue(withIdentifier: "HomeTabSegue", sender: self)
                    NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
                }
                else
                {
                    self.fbLogin.readPermissions = ["public_profile", "email"]
                    self.fbLogin.delegate = self
                    self.fbLogin.isHidden = false
                }
            }
        }

        func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
            if let error = error {
                print(error.localizedDescription)
                return
            }

            guard let authentication = user.authentication else { return }
            let credential = FIRGoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                              accessToken: authentication.accessToken)
            FIRAuth.auth()?.signIn(with: credential) { (user, error) in
                self.databaseRef = FIRDatabase.database().reference()
                self.databaseRef.child("Users").child(user!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
                    let snapshot = snapshot.value as? NSDictionary
                    if(snapshot == nil)
                    {
                        self.databaseRef.child("Users").child(user!.uid).setValue(["name" : user?.displayName, "email": user?.email])
                    }
                })

            }
        }
        func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
            if let error = error {
                print(error.localizedDescription)
                return
            }

            try! FIRAuth.auth()!.signOut()

        }


        func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
            print("user has log in fb")

            let activityData = ActivityData()

            NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData)

            self.fbLogin.isHidden = true

            if (error != nil)
            {
                NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
                print(error.localizedDescription)
                self.fbLogin.isHidden = false
            }
            else if(result.isCancelled)
            {
                print("cancelled is pressed")
                NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
                self.fbLogin.isHidden = false
            }
            else
            {
                let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
                FIRAuth.auth()?.signIn(with: credential) { (user, error) in
                    print("user has log into firebase")
                self.databaseRef = FIRDatabase.database().reference()
                self.databaseRef.child("Users").child(user!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
                    let snapshot = snapshot.value as? NSDictionary
                    if(snapshot == nil)
                        {
                            self.databaseRef.child("Users").child(user!.uid).setValue(["name" : user?.displayName, "email": user?.email])
                        }
                    })
                }
            }
        }

        func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
            print("user has log out")
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }

So far my code works in saving users to firebase both in facebook and google.It's just that when signing when google it doesnt ask my permission while when signing in facebook it does. Pls give me a correct way how to log in multiple auth or a good project example would be nice coz i saw none with a project just implementing these. Give me idea pls.

2条回答
在下西门庆
2楼-- · 2019-04-15 18:36

I guess your problem is not call GIDSignIn sign in function in your loginViewController:

@IBAction func signInButtonDidTouch(_ sender: Any) {

    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().delegate = self

    if GIDSignIn.sharedInstance().hasAuthInKeychain() {
        GIDSignIn.sharedInstance().signInSilently()
    } else {
        GIDSignIn.sharedInstance().signIn()
    }
}

The code above I had custom GG sign in button @IBOutlet weak var signInButton: GIDSignInButton!

查看更多
Fickle 薄情
3楼-- · 2019-04-15 18:53

I think in application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool, you need to get the result of GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation) and return it along with FB's too. So it should be something like this:

return handled || GIDSignIn.sharedInstance().handle(url,
                                      sourceApplication: sourceApplication,
                                      annotation: annotation)

Because according to the documentation here:

Returns YES if GIDSignIn handled this URL.

查看更多
登录 后发表回答