user3766930 user3766930 - 1 month ago 9
Swift Question

how can I convert NSArray into specific String?

I'm using

facebook-api
to fetch user's friends. The code is as follows:

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


The
resultDict
contains:

{
data = (
{
id = 1662200084096651;
}
);
paging = {
cursors = {
after = QVFIUmFsa0JGazI4amNEcFczT0NRQzdiNshusdsDSHFDHFDDSm02UzNudV9ZATS1ESk5iUEQ5T2syNGDSw4yegdxbdf4WGZA3;
before = QVFIUmFsa0JGazI4amNEcFczT0NRQzdiNURGQTgdsgdsHFDSHTRTNU9DSm02UzNudV9ZATS1ESk5iUEQ5T2syNkRjQW8xc1drGgdsGREHRTcXE4WGZA3;
};
};
summary = {
"total_count" = 762;
};
}


The
print
above prints (for 1 fb friend):

(
{
id = 1020XXXXXX305XXX;
}
)

I want to pass this to my server, so I thought about doing:

var emptyParams = ["":""]
emptyParams["friends"] = (defaults.objectForKey("fb_friends") as! NSArray).componentsJoinedByString(",")


but then instead of params:

friends: 1020XXXXXX305XXX


I have:

"friends": {
id = 10206503694305180;
}


I want to skip the
id
and send it as an array, because on my server I have:

var friends = req.body.friends;
for(var i=0; i<friends.length; i++) {
console.log(friends[i]);
query = query.or([{ 'fb_friend': friends[i] }]);
}


how should my modify my
swift
code so that it creates a correct request?

Answer

From what I understand of your code, fb_friends have type of [[String:String]] and you want convert it to [String]?

You can use .map to get "id" from the dictionary.

let friends = (defaults.objectForKey("fb_friends") as! NSArray)
    .map{$0["id"]!}
    .joinWithSeparator(",")
let params = [
  "friends": friends
]
Comments