Get Facebook email and save to Parse.com

622 views Asked by At

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)
}
2

There are 2 answers

2
Kumuluzz On BEST ANSWER

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"]
0
Frederico On

For those updating to Xcode 7 and Swift 2.0, this is the syntax:

override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated)

if (PFUser.currentUser() == nil) {
    self.loginViewController.fields = 
    [PFLogInFields.UsernameAndPassword, 
    PFLogInFields.LogInButton, 
    PFLogInFields.SignUpButton, 
    PFLogInFields.PasswordForgotten, 
    PFLogInFields.DismissButton, 
    PFLogInFields.Twitter, 
    PFLogInFields.Facebook]

    self.loginViewController.delegate = self
    self.signupViewController.delegate = self

    self.presentViewController(loginViewController, animated: true, completion: nil)
}

}