我正在使用facebook-api
来抓取用户的朋友。代码如下:
let params = ["fields": "id"]
let request = FBSDKGraphRequest(graphPath: "me/friends", parameters: params)
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error != nil {
let errorMessage = error.localizedDescription
print(errorMessage)
/* Handle error */
}
else if result.isKindOfClass(NSDictionary){
/* handle response */
let defaults = NSUserDefaults.standardUserDefaults()
let resultdict = result as! NSDictionary
let data : NSArray = resultdict.objectForKey("data") as! NSArray
for i in 0..<data.count {
let valueDict : NSDictionary = data[i] as! NSDictionary
let id = valueDict.objectForKey("id") as! String
print("the id value is \(id)")
}
let friends = resultdict.objectForKey("data") as! NSArray
print("Found \(friends.count) friends")
print(friends)
defaults.setObject(friends, forKey: "fb_friends")
defaults.synchronize()
}
}
resultDict
包含:
{
data = (
{
id = 1662200084096651;
}
);
paging = {
cursors = {
after = QVFIUmFsa0JGazI4amNEcFczT0NRQzdiNshusdsDSHFDHFDDSm02UzNudV9ZATS1ESk5iUEQ5T2syNGDSw4yegdxbdf4WGZA3;
before = QVFIUmFsa0JGazI4amNEcFczT0NRQzdiNURGQTgdsgdsHFDSHTRTNU9DSm02UzNudV9ZATS1ESk5iUEQ5T2syNkRjQW8xc1drGgdsGREHRTcXE4WGZA3;
};
};
summary = {
"total_count" = 762;
};
}
以上print
打印(适用于1个朋友):
( { id = 1020XXXXXX305XXX; } )
我想把它传递给我的服务器,所以我想到了:
var emptyParams = ["":""]
emptyParams["friends"] = (defaults.objectForKey("fb_friends") as! NSArray).componentsJoinedByString(",")
然后而不是params:
friends: 1020XXXXXX305XXX
我有:
"friends": {
id = 10206503694305180;
}
我想跳过id
并将其作为数组发送,因为在我的服务器上我有:
var friends = req.body.friends;
for(var i=0; i<friends.length; i++) {
console.log(friends[i]);
query = query.or([{ 'fb_friend': friends[i] }]);
}
我应该如何修改我的swift
代码以便创建正确的请求?
答案 0 :(得分:1)
根据我对您的代码的理解,fb_friends
的类型为[[String:String]]
,您希望将其转换为[String]
吗?
您可以使用.map
从字典中获取"id"
。
let friends = (defaults.objectForKey("fb_friends") as! NSArray)
.map{$0["id"]!}
.joinWithSeparator(",")
let params = [
"friends": friends
]