Search code examples
iosswiftparse-platformfacebook-ios-sdk

Get Facebook email and save to Parse.com


The below code adds the parse login and signup forms. But when I use the Facebook fields, it logs in the user but it does not update the email fields.

Is there a way I can get the email field updated?

func showLogInPage() {
    var loginViewController = PFLogInViewController()
    loginViewController.delegate = self
    loginViewController.fields = (PFLogInFields.UsernameAndPassword | PFLogInFields.LogInButton | PFLogInFields.SignUpButton | PFLogInFields.PasswordForgotten | PFLogInFields.Facebook)
    var signupViewController = PFSignUpViewController()
    signupViewController.delegate = self
    loginViewController.signUpController = signupViewController
    self.presentViewController(loginViewController, animated: true, completion: nil)
}

Solution

  • Inside of the PFLogInViewControllerDelegate there is a callback which is triggered when logging in with Facebook called logInViewController:didLogInUser. In here you can retrieve the email from the Facebook SDK and store it in the PFUser. I've made a small example here:

    // MARK: - PFLogInViewControllerDelegate
    
    func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
        updatePFUserEmail()
    }
    
    func updatePFUserEmail() {
        if (FBSDKAccessToken.currentAccessToken() != nil) {
            FBSDKGraphRequest(graphPath: "me", parameters: nil).startWithCompletionHandler({ (connection, result, error) in
                if (error != nil) { return }
                if let user = result as? NSDictionary {
                    if let email = user.objectForKey("email") as? String {
                        PFUser.currentUser()?.email = email
                        PFUser.currentUser()?.saveInBackground()
                    }
                    else {
                        PFUser.currentUser()?.email = ""
                        PFUser.currentUser()?.saveInBackground()
                    }
                }
            })
        }
    }
    

    UPDATE 1

    Missing the FB permission settings


    You need to specify the Facebook permission in your showLogInPage to read the user's email. You can do this in the following way:

    loginViewController.facebookPermissions = ["email"]