web-dev-qa-db-fra.com

iOS facebookSDK obtenir les détails complets de l'utilisateur

J'utilise le dernier FBSDK (avec Swift)

// MARK: sign in with facebook

func signInWithFacebook()
{
    if (FBSDKAccessToken.currentAccessToken() != nil)
    {
        // User is already logged in, do work such as go to next view controller.
        println("already logged in ")
        self.returnUserData()

        return
    }
    var faceBookLoginManger = FBSDKLoginManager()
    faceBookLoginManger.logInWithReadPermissions(["public_profile", "email", "user_friends"], handler: { (result, error)-> Void in
        //result is FBSDKLoginManagerLoginResult
        if (error != nil)
        {
            println("error is \(error)")
        }
        if (result.isCancelled)
        {
            //handle cancelations
        }
        if result.grantedPermissions.contains("email")
        {
            self.returnUserData()
        }
    })
}

func returnUserData()
{
    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

        if ((error) != nil)
        {
            // Process error
            println("Error: \(error)")
        }
        else
        {
            println("the access token is \(FBSDKAccessToken.currentAccessToken().tokenString)")

            var accessToken = FBSDKAccessToken.currentAccessToken().tokenString

            var userID = result.valueForKey("id") as! NSString
            var facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"



            println("fetched user: \(result)")


}

quand j'imprime l'utilisateur récupéré, je n'obtiens que l'ID et le nom! , mais j'ai demandé une permission pour le courrier électronique, les amis et le profil, qu'est-ce qui ne va pas ???

BTW: J'ai déplacé ce projet de mon macbook vers un autre macbook (parce que j'ai formaté le mien), cela fonctionnait très bien quand c'était sur le macbook sur lequel j'avais créé le projet, mais après avoir déplacé le projet (en utilisant bitbucket clone), j'ai obtenu ces résultats .

16
user3703910

Selon le nouveau SDK de Facebook, vous devez obligatoirement transmettre les paramètres avec la variable FBSDKGraphRequest

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

Documentations Link: https://developers.facebook.com/docs/facebook-login/permissions/v2.4

Référence d'objet utilisateur: https://developers.facebook.com/docs/graph-api/reference/user

Avec le profil public, vous pouvez obtenir le genre: 

public_profile (Default)

Provides access to a subset of items that are part of a person's public profile. A person's public profile refers to the following properties on the user object by default:

id
name
first_name
last_name
age_range
link
gender
locale
timezone
updated_time
verified
41
Ashish Kakkad

Swift 4

Un exemple dans Swift 4 qui montre également comment analyser correctement les champs individuels du résultat:

func fetchFacebookFields() {
    //do login with permissions for email and public profile
    FBSDKLoginManager().logIn(withReadPermissions: ["email","public_profile"], from: nil) {
        (result, error) -> Void in
        //if we have an error display it and abort
        if let error = error {
            log.error(error.localizedDescription)
            return
        }
        //make sure we have a result, otherwise abort
        guard let result = result else { return }
        //if cancelled nothing todo
        if result.isCancelled { return }
        else {
            //login successfull, now request the fields we like to have in this case first name and last name
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name"]).start() {
                (connection, result, error) in
                //if we have an error display it and abort
                if let error = error {
                    log.error(error.localizedDescription)
                    return
                }
                //parse the fields out of the result
                if
                    let fields = result as? [String:Any],
                    let firstName = fields["first_name"] as? String,
                    let lastName = fields["last_name"] as? String
                {
                    log.debug("firstName -> \(firstName)")
                    log.debug("lastName -> \(lastName)")
                }
            }
        }
    }
}
6
HixField

Je suppose que ce code devrait vous aider à obtenir les détails requis

Swift 2.x

let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

        if ((error) != nil)
        {
            // Process error
            print("Error: \(error)")
        }
        else
        {
            print("fetched user: \(result)")
            let userName : NSString = result.valueForKey("name") as! NSString
            print("User Name is: \(userName)")
            let userID : NSString = result.valueForKey("id") as! NSString
            print("User Email is: \(userID)")



        }
    })
4
Rizwan Ahmed

Dans Swift 4.2 et Xcode 10.1

@IBAction func onClickFBSign(_ sender: UIButton) {

    if let accessToken = AccessToken.current {
        // User is logged in, use 'accessToken' here.
        print(accessToken.userId!)
        print(accessToken.appId)
        print(accessToken.authenticationToken)
        print(accessToken.grantedPermissions!)
        print(accessToken.expirationDate)
        print(accessToken.declinedPermissions!)

        let request = GraphRequest(graphPath: "me", parameters: ["fields":"id,email,name,first_name,last_name,picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
        request.start { (response, result) in
            switch result {
            case .success(let value):
                print(value.dictionaryValue!)
            case .failed(let error):
                print(error)
            }
        }

        let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
        self.present(storyboard, animated: true, completion: nil)
    } else {

        let loginManager=LoginManager()

        loginManager.logIn(readPermissions: [ReadPermission.publicProfile, .email, .userFriends, .userBirthday], viewController : self) { loginResult in
            switch loginResult {
            case .failed(let error):
                print(error)
            case .cancelled:
                print("User cancelled login")
            case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                print("Logged in : \(grantedPermissions), \n \(declinedPermissions), \n \(accessToken.appId), \n \(accessToken.authenticationToken), \n \(accessToken.expirationDate), \n \(accessToken.userId!), \n \(accessToken.refreshDate), \n \(accessToken.grantedPermissions!)")

                let request = GraphRequest(graphPath: "me", parameters: ["fields": "id, email, name, first_name, last_name, picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
                request.start { (response, result) in
                    switch result {
                    case .success(let value):
                        print(value.dictionaryValue!)
                    case .failed(let error):
                        print(error)
                    }
                }

                let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
                self.navigationController?.pushViewController(storyboard, animated: true)

            }
        }
    }

}

https://developers.facebook.com/docs/graph-api/reference/user

0
iOS