获取Facebook电子邮件并保存到Parse.com

时间:2015-06-09 09:59:12

标签: ios swift parse-platform facebook-ios-sdk

以下代码添加了解析登录和注册表单。但是当我使用Facebook字段时,它会登录用户,但不会更新电子邮件字段。

有没有办法让电子邮件字段更新?

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 个答案:

答案 0 :(得分:2)

PFLogInViewControllerDelegate内部有一个回调,在使用Facebook登录时会触发logInViewController:didLogInUser。在这里,您可以从Facebook SDK检索电子邮件并将其存储在PFUser中。我在这里做了一个小例子:

// 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()
                }
            }
        })
    }
}

更新1

缺少FB权限设置

您需要在showLogInPage中指定Facebook权限才能阅读用户的电子邮件。您可以通过以下方式执行此操作:

loginViewController.facebookPermissions = ["email"]

答案 1 :(得分:0)

对于那些更新到Xcode 7和Swift 2.0的人,这是语法:

覆盖func viewDidAppear(动画:Bool) {     super.viewDidAppear(动画)

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

}