简体   繁体   English

如何在iOS(Swift4)中从facebook获取profile_picture和friends_lists?

[英]How to get profile_picture and friends_lists from facebook in iOS(Swift4)?

I am working on iOS app and I need to get the users friend list from facebook and also the profile picture. 我正在使用iOS应用程序,我需要从Facebook获取用户朋友列表以及个人资料图片。 However I can Sign in without a problem but still need this two pieces of information.. This is my code: 但是,我可以毫无问题地登录,但仍然需要这两条信息。这是我的代码:

@IBAction func loginFBAction(_ sender: UIButton) {
    let fbLoginManager:FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
        if error != nil {
            let fbLoginresult:FBSDKLoginManagerLoginResult = result!
            if(fbLoginresult.grantedPermissions.contains("email"))
            {
                print(fbLoginresult)
                self.getFBUserData()
                fbLoginManager.logOut()
            }
            print("Process error")
        }
        else if (result?.isCancelled)! {
            print("Cancelled")
        }
        else{
            print("Logged in")

 func getFBUserData() {
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                //everything works print the user data
                print(result as Any)
            }})
    }
}

Your code doesn't work because you call getFBUserData at wrong place. 您的代码无效,因为您在错误的位置调用了getFBUserData

In fbLoginManager.logIn you check if error is not nil - it's mean if Facebook SDK return error during login. fbLoginManager.logIn ,检查错误是否不是fbLoginManager.logIn这意味着Facebook SDK在登录期间返回错误。 And in your code you want to fetch user data if you have an error. 并且在您的代码中,如果发生错误,您希望获取用户数据。 So because you do not have an error and user is successfully log in this code do not execute. 因此,因为您没有错误并且用户成功登录,所以此代码不执行。

Place this call after print("Logged in") and it should work. 将此调用print("Logged in") ,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM