Get email and name Facebook SDK v4.4.0 Swift

前端 未结 10 2138
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 02:22

TL;TR: How do I get the email and name of a user that is logged in on my app using the facebook SDK 4.4

So far I have managed to get login working, now I can get the

10条回答
  •  清歌不尽
    2020-12-08 02:42

    I've used fields in android, so I figured to try it in iOS as well, and it works.

    let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: accessToken.tokenString, version: nil, HTTPMethod: "GET")
       req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
           if(error == nil) {
                print("result \(result)")
           } else {
                print("error \(error)")
           }
       }
    )
    

    result will print:

    result {
       email = "email@example.com";
       id = 123456789;
       name = "Your Name";
    }
    

    Found that these fields are equal to the User endpoint, see this link where you can see all the fields that you can get.

    Update for Swift 4 and above

    let r = FBSDKGraphRequest(graphPath: "me",
                              parameters: ["fields": "email,name"],
                              tokenString: FBSDKAccessToken.current()?.tokenString,
                              version: nil,
                              httpMethod: "GET")
    
    r?.start(completionHandler: { test, result, error in
        if error == nil {
            print(result)
        }
    })
    

    Update for Swift 5 with FBSDKLoginKit 6.5.0

    guard let accessToken = FBSDKLoginKit.AccessToken.current else { return }
    let graphRequest = FBSDKLoginKit.GraphRequest(graphPath: "me",
                                                  parameters: ["fields": "email, name"],
                                                  tokenString: accessToken.tokenString,
                                                  version: nil,
                                                  httpMethod: .get)
    graphRequest.start { (connection, result, error) -> Void in
        if error == nil {
            print("result \(result)")
        }
        else {
            print("error \(error)")
        }
    }
    

提交回复
热议问题