Get Facebook user details with swift and parse
Asked Answered
I

2

5

i need to get the Facebook user information details when i login a new user through parse. at present i am logging in the new user below. can't seem to get the user details though. I've seen some code written on objective - c. most of the functions don't work anymore

The Facebook iOS sdks i am running is v4.3.0.

@IBAction func facebookButton(sender: AnyObject) {

    PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
        (user: PFUser?, error: NSError?) -> Void in
        if let user = user {
            if user.isNew {
                println("User signed up and logged in through Facebook!")
            } else {
                println("User logged in through Facebook!")
            }
        } else {
            println("Uh oh. The user cancelled the Facebook login.")
        }
    }
}
Ismaelisman answered 6/7, 2015 at 11:7 Comment(0)
C
10

To get the user details you have to send a FBSDKGraphRequest after the login request.

This can be done inside the if let user = user {...} block.

    // Create request for user's Facebook data
    let request = FBSDKGraphRequest(graphPath:"me", parameters:nil)

    // Send request to Facebook
    request.startWithCompletionHandler {

        (connection, result, error) in

        if error != nil {
            // Some error checking here
        }
        else if let userData = result as? [String:AnyObject] {

            // Access user data
            let username = userData["name"] as? String

            // ....
        }
    }               
Candlemaker answered 6/7, 2015 at 12:36 Comment(4)
Hi I'm trying to fetch user email using let username = userData["name"] as? String but it's showing nil. I'm getting the user name successfully.Polyzoic
I fixed it. You need to have parameters:["fields":"id,email,name,first_name,last_name"]Polyzoic
How to access this outside the request though? Like I wanna use the username somewhere else. How to do it?Talya
@GustavoFulton: You can assign username to a class variable or you can call a class method inside the callback block after startWithCompletionHandlerCandlemaker
K
1

For the new Facebook API and version of Swift 3.1 you can do something like this:

if((FBSDKAccessToken.current()) != nil) {
    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,name,first_name,last_name,email"]).start(completionHandler: {(connection, result, error) -> Void in

        if(error != nil) {
            print("Some error occurred.");
        } else {
            print(result!)
        }
    })
}
Kwangju answered 10/4, 2017 at 15:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.