iOS FacebookSDK获取用户完整信息

18

我正在使用最新的FBSDK(使用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)")


}

当我打印获取的用户时,我只得到了id和姓名!但是我请求了email、friends和profile的权限,出了什么问题?

顺便说一下:我把这个项目从我的Macbook移到了另一台Macbook上(因为我格式化了我的Macbook),在我创建项目的Macbook上它运行得非常好,但是在移动项目后(使用Bitbucket克隆)我得到了这些结果。


1
请参考以下链接,希望能解决您的问题:https://dev59.com/e4vda4cB1Zd3GeqPbZnH#30634444 @user3703910 - Dharmesh Dhorajiya
问题已在重复帖子中得到解决:https://dev59.com/cF0Z5IYBdhLWcg3wdQTU#31503463 - HeTzi
4个回答

44
根据最新的Facebook SDK,你必须通过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)
        }
    })
}

文档链接: https://developers.facebook.com/docs/facebook-login/permissions/v2.4

用户对象参考: https://developers.facebook.com/docs/graph-api/reference/user

使用公共个人资料可以获取性别:

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

你能指导我到他们的文档吗?而且我怎么获取性别信息呢? - user3703910
如何从结果中获取值?我需要获取电子邮件地址、名字和姓氏等信息。怎么做呢?我尝试使用 result.valueForKey("email"),但没有帮助我。 - Noorul

10

Swift 4

以下是一个 Swift 4 的示例,同时演示了如何正确地解析出结果中的各个字段:

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

Swift 4 的好例子,倒数第二行有错别字,应该是 firstName 而不是 firsName。 - shokaveli
@HixField 非常感谢。。代码在iOS 11.4上运行良好。 - Vinayak Bhor

4
我想这段代码可以帮助您获取所需的详细信息。 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)")



        }
    })

获取类型为“Any?”的值没有“valueForKey”成员错误消息。 - Jayprakash Dubey
上面的答案适用于Swift 2.x,现在在Swift 3.x中尝试像这样使用它。(我也会为Swift 3更新上面的答案)let data:[String:AnyObject] = result as! [String : AnyObject]print(data["first_name"]!) print(data["id"]!) - Rizwan Ahmed

1
在Swift 4.2和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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接