Facebook好友列表另存为数组到Parse - Swift

san*_*ner 1 facebook-login parse-platform ios9 swift2

我想将我从facebook获取的朋友列表ID转换为数组以保存在解析中.我的代码如下所示,但我得到一个"意外发现nil,同时解开一个Optional值"错误.如果需要,我该怎么做才能保存结果以解析并将其作为数组检索?

  let fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
                fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in

                    if error == nil {

                        print("Friends are : \(result)")

                        if let dict = result as? Dictionary<String, AnyObject>{

                            let profileName:NSArray = dict["name"] as AnyObject? as! NSArray
                            let facebookID:NSArray = dict["id"] as AnyObject? as! NSArray

                            print(profileName)
                            print(facebookID)

                    }

                    }
                        else {

                        print("Error Getting Friends \(error)");

                    }
                }
Run Code Online (Sandbox Code Playgroud)

当我在print()中使用下面的代码时,我得到以下结果:

 Friends are : {
data =     (
            {
        id = 138495819828848;
        name = "Michael";
    },
            {
        id = 1105101471218892;
        name = "Johnny";
    }
);
Run Code Online (Sandbox Code Playgroud)

Rus*_*ell 5

问题是您正在尝试从顶级字典访问nameid您需要访问的元素data.

当您为朋友调用FB Graph API时,它将返回一个字典数组(每个朋友一个).

试试这个:

let fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil)
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in

    if error == nil {

        print("Friends are : \(result)")

        if let friendObjects = result["data"] as? [NSDictionary] {
            for friendObject in friendObjects {
                println(friendObject["id"] as NSString)
                println(friendObject["name"] as NSString)
            }
        }
    } else {
        print("Error Getting Friends \(error)");
    }
}
Run Code Online (Sandbox Code Playgroud)

您还应该查看此SO帖子,了解有关FB Graph API的更多信息.这是一个简短的片段.

在Graph API的v2.0中,调用/ me/friends返回同时使用该应用程序的人的朋友.

此外,在v2.0中,您必须向每个用户请求user_friends权限.默认情况下,每次登录都不再包含user_friends.每个用户必须授予user_friends权限才能出现在/ me/friends的响应中.有关更多详细信息,请参阅Facebook升级指南,或查看下面的摘要.