Facebook 好友列表另存为要解析的数组 - Swift

Facebook Friend List Save As Array to Parse - Swift

我想将从 facebook 获取的朋友列表 ID 转换为数组以保存在解析中。我的代码如下,但出现 "unexpectedly found nil while unwrapping an Optional value" 错误。我应该如何保存结果以在需要时将其作为数组进行解析和检索?

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

                    }
                }

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

 Friends are : {
data =     (
            {
        id = 138495819828848;
        name = "Michael";
    },
            {
        id = 1105101471218892;
        name = "Johnny";
    }
);

问题是您正在尝试访问顶级词典中的 nameid 元素,而您需要在其中访问 data.

当您为朋友调用 FB 图 API 时,它将 return 一组字典(每个朋友一个)。

试试这个:

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

您还应该查看 this SO post with more information on the FB Graph API。这是一个简短的片段。

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.