So, I am trying to get a list of all other facebook friends also connected on my app.
After doing an FBSDKgraphrequest, I get the right data (see below) and then convert it to an NSDictionary. The data looks like this:
{
friends = {
data = (
{
id = 10154257515635281;
name = "Hector Judd";
},
{
id = 151132798649181;
name = "Arch Tester Dev";
}
);
paging = {
cursors = {
after = QVFIUndVRFZAINXhCSlAzdnNGeUUwTHdhamNpc3NFbjR2NjF4dk40N3ZAZAR2lNLXM0Q3BxLW90REVsaFk3aU13Um1Ca0NOd0ZAXN2gxaDF2emhYem9BMjhkMVl3;
before = QVFIUlo2a1Q4UGhpWmY2SFNWbUtpMVcxZAnEtR01KSlUyeVEtMU9GbjNkRHp2bTFKY0VoVm5xX3dNLXEwMG5OY0Q0My0ZD;
};
};
summary = {
"total_count" = 831;
};
};
id = 10208811056967519;
}
I then try and unpack it with multiple if let statements, but end up getting the error: Segmentation fault 11. See code below.
func getFriends() {
let parameters = ["fields": "friends"]
FBSDKGraphRequest(graphPath: "me", parameters: parameters).startWithCompletionHandler({ (connection, result, error) -> Void in
if error != nil {
print(error)
} else {
if let result = result as? NSDictionary {
if let data = result["friends"] as? NSDictionary {
if let friendData = data["data"] as? NSArray {
for friend in friendData {
friendIds.append(friend["id"] as String)
print(friendIds)
}
}
}
}
}
})
}
I am relatively new to programming and am struggling to work out a good way to do this. Any suggestions would be much appreciated!! Thanks.
Try to declare your friendData variable as a NSDictionary in your Loop
for friend in friends {
if let friendData = friend as? NSDictionary {
friendIds.append(friendData["id"] as! String)
}
}
Related
I'm beginner in iOS programming but I work in android so now I stuck in a problem in iOS.
I know my question is general but I really need your help!
in android for connect to server we do like below:
Call<String> myList = service.Contact_List("");
myList.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try{
ArrayList<Contact> contactArrayList = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response.body());
for(int i=0 ; i<jsonArray.length() ; i++)
contactArrayList.add(gson.fromJson(jsonArray.getJSONObject(i).toString(), Contact.class));
}catch (Exception e) {
Log.d("Catch","Error")
}finally {
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("Failure","Error")
}
});
and in xcode I do like below :
let url = URL(string: "http://api.example.com/Contact-List")
Alamofire.request(url!, method: HTTPMethod.post, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
print("response.request")
print(response.request as Any) // original URL request
print("response.response")
print(response.response as Any) // URL response
print("response.result.value")
}
and my result is something like this:
[{"Id":1,"Name":"Mary","TelNumber":"09111111"},{"Id":2,"Name":"Sarah","TelNumber":"09222222"},
{"Id":3,"Name":"Ben","TelNumber":"09333333"}]
now my question is that how can I do like this code in Xcode(swift 3 ):
for(int i=0 ; i<jsonArray.length() ; i++)
contactArrayList.add(gson.fromJson(jsonArray.getJSONObject(i).toString(), Contact.class));
in addition, I use ASP.net in server side.
I am really sorry about my long and ambiguous question!
thanks for any suggestions.
First create NSObject swift file :
then add code
class demo {
var ID: String
var Name: String
init(ID: String, Name: String) {
self.ID = ID
self.Name = Name
}
}
Try like this way :
let data = response.result.value
if data != nil {
self.presentWindow.hideToastActivity()
if let response = data as? [[String: AnyObject]] {
for detail_data in response {
let Id = detail_data["Id"] as? String ?? ""
let Name = detail_data["Name"] as? String ?? ""
let demoObj = demo(ID: ID, Name: Name
self.demoObjects.append(demoObj)
}
}
}
Updated Answer
for converting string response to JSON
Sample code will be something like this. Don't forget to handle unwrap stuff
let data1 = "[{\"Id\": 1,\"Name\": \"Mary\",\"TelNumber\": \"09111111\"},{\"Id\": 2,\"Name\": \"Sarah\",\"TelNumber\": \"09222222\"}]" //your JSON From API Response
let data = data1.data(using: .utf8)
do {
let array = try JSONSerialization.jsonObject(with: data!) as! [[String : Any]]
for detail_data in array {
let Id = detail_data["Id"] as? Int ?? 00
let Name = detail_data["Name"] as? String ?? ""
print("Id:",Id)
print("Name:",Name)
print("****")
}
} catch {
print("Exception occured \(error))")
}
I have been searching every where, but cannot get to the right answer. I receive a Json result with the following structure
{
result = {
"2ab5a003-0120-4c01-80f2-a237dcf4ba14" = {
icon = garden;
id = "2ab5a003-0120-4c01-80f2-a237dcf4ba14";
index = 1;
name = "Tafel hoek";
parent = "855113f1-f488-4223-b675-2f01270f573e";
};
"2afd6093-ca6d-4e52-aaca-336ab76ea454" = {
icon = default;
id = "2afd6093-ca6d-4e52-aaca-336ab76ea454";
index = 11;
name = Badkamer;
parent = "9919ee1e-ffbc-480b-bc4b-77fb047e9e68";
};
};
status = 200;
}
Because I don't know the 1st key in the result I am lost to get the separate items. Is there any one who can help me ? Thanks in advance
my code is:
{ print("Error: ")
print(error!)
} else { // no error
if let urlContent = data { // 3
do { // 4
let json = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(json)
} catch {
print("JSON processing failed")
} // end 4 do
} // end 3 let urlContent
} // end 2 if error}
Since you have the dictionary for key result, you can enumerate it as usual:
if let result = json["result"] as? [String:[String:Any]] {
for (key, value) in result {
let name = value["name"] as! String
let index = value["index"] as! Int
print (key, name, index)
}
}
Can you post your code ,i think that is not a valid json format and tell me where you are struggling to parse.ignore that key and try as usual
I have a complex JSON data.
How can I parse this data?
I've tried, but it does not work.
I need a Dictionary with object (id, time...). But how to get through "1,.."?
And how can I take time begin and end?
"data": {
"1":[
{"id":6524612,
...
"time":{
"begin":"18:50",
"end":"19:20"
},
...
},
"2":[
{
"id":6524613,
...
"time":{
"begin":"18:50",
"end":"19:20"
},
...
},
Where is my mistake?
let broadcastTask = broadcastSession.dataTaskWithRequest(broadcastRequest) { (data, response, error) -> Void in
if error != nil {
print(error.debugDescription)
} else {
do {
let broadcastDict = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? Dictionary<String, AnyObject>
if let results = broadcastDict!["data"] as? [Dictionary<String, AnyObject>] {
for obj in results {
let broadcast = Broadcast(broadcastDict: obj)
self.broadcastList.append(broadcast)
}
//Main UI thread
dispatch_async(dispatch_get_main_queue()) {
self.collectionView.reloadData()
}
}
} catch {
}
}
}
broadcastTask.resume()
init(broadcastDict: Dictionary<String, AnyObject>) {
if let category = broadcastDict["id"] as? Int {
self.id = id
}
...
}
If I understand the question correctly:
The first problem seems to be that you are trying to cast the "data" dictionary to an array of dictionaries. This will always fail because your data object is a dictionary and not an array.
Once you correct that problem you will run into trouble with your loop. Try this:
for (key, value) in results {
let broadcast = Broadcast(broadcastDict: value)
self.broadcastList.append(broadcast)
}
Now you are sending the dictionary that your Broadcast object is expecting.
Been working on pulling data from an API, finally got that to work (I believe correctly) but when I print out variables within the dictionary, "Optional" gets added to the string
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary
print(jsonResult)
if (jsonResult != nil) {
if let players = jsonResult?["players"] as? [Dictionary<String, AnyObject>] {
for player in players {
let personID = player["name"]
print(personID)
}
}
} else {
print("No Data")
// couldn't load JSON, look at error
}
}
Sample of the JSON Output:(note I cut this down and used only the first element)
Optional({
players = (
{
name = "Derek Anderson";
},
Print statement:
Optional(Derek Anderson)
My assumption here is that its printing the Optional Dictionary and then grabbing the "players" name. Meaning I haven't pulled just that name out. I've pulled the name out of the players array, not the Optional.
I feel like I may be adding that Optional Array in some way though, cant seem to figure this one out!
Solved, the variable needs to be unwrapped:
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary
print(jsonResult)
if (jsonResult != nil) {
if let players = jsonResult?["players"] as? [Dictionary<String, AnyObject>] {
for player in players {
let personID = player["name"]!
print(personID)
}
}
} else {
print("No Data")
// couldn't load JSON, look at error
}
}
In Swift, I have a POST request to a URL which returns JSON similar to this:
{"users":[{
"user":{"userID":"1","userName":"John"}},
{"user":{"userID":"2","userName":"Mary"}},
{"user":{"userID":"3","userName":"Steve"}},
]}
Here's the Swift code:
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
println(result?.count)
println(result)
...Which outputs this:
Optional(1)
Optional({
users = ({
user = {
userID = 1;
userName = John;
};
},
{
user = {
userID = 2;
userName = Mary;
};
},
{
user = {
userID = 3;
userName = "Steve";
};
});
})
I'm trying to loop through the "user" elements but nothing I try is working. I have a dictionary of the "user" level JSON, but don't know how to go on to get the child "users" of this. Does anyone know how I can do this? If I could look through them to println() the users' names that would be a great start.
Try this.
var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
if let users = result?.objectForKey("users") as? [[String:AnyObject]]
{
for user in users
{
if let userValues = user["user"] as? [String:AnyObject]
{
println(userValues["userID"]!)
println(userValues["userName"]!)
}
}
}