I'm new to ios and its developing. i have clean code with set Correctly AFNetworking.My base URl's json Encording has got JSON objects and arrays as well as values . in my JSON out put i want to get values of "thumbnail" every time i do im getting Null .please help me to get "name ,thumbnail,id,images " of my json output. please find my NSDictionary type printed object's NSlog.
2014-07-20 09:08:33.110 WADTourisum[1157:60b] Reachability Flag Status: -R ------- networkStatusForFlags
2014-07-20 09:08:33.879 WADTourisum[1157:60b] JSON: {
Main = (
{
id = 1;
"image_bundle_id" = 1;
images = (
"http://wearedesigners.net/clients/clients12/tourism/images/guides/oceans/slide_images/1.jpg",
"http://wearedesigners.net/clients/clients12/tourism/images/guides/oceans/slide_images/2.jpg",
"http://wearedesigners.net/clients/clients12/tourism/images/guides/oceans/slide_images/3.jpg"
);
name = OCEAN;
thumbnail = "http://wearedesigners.net/clients/clients12/tourism/images/guides/thumbs/ocean.jpg";
},
{
id = 2;
"image_bundle_id" = 23;
images = (
"http://wearedesigners.net/clients/clients12/tourism/images/guides/heritages/slide_images/1.jpg",
"http://wearedesigners.net/clients/clients12/tourism/images/guides/heritages/slide_images/2.jpg",
"http://wearedesigners.net/clients/clients12/tourism/images/guides/heritages/slide_images/3.png"
);
name = Heritage;
thumbnail = "http://wearedesigners.net/clients/clients12/tourism/images/guides/thumbs/heritage.jpg";
},
{
id = 3;
"image_bundle_id" = 0;
images = (
);
name = "Tea Country";
thumbnail = "http://wearedesigners.net/clients/clients12/tourism/images/guides/thumbs/teaCountry.jpg";
},
{
id = 4;
"image_bundle_id" = 0;
images = (
);
name = "WILD LIFE";
thumbnail = "http://wearedesigners.net/clients/clients12/tourism/images/guides/thumbs/wildLife.jpg";
},
{
id = 5;
"image_bundle_id" = 0;
images = (
);
name = Culture;
thumbnail = "http://wearedesigners.net/clients/clients12/tourism/images/guides/thumbs/culture.jpg";
},
{
id = 6;
"image_bundle_id" = 0;
images = (
);
name = "NIGHT LIFE";
thumbnail = "http://wearedesigners.net/clients/clients12/tourism/images/guides/thumbs/nightLife.jpg";
}
);
}
my code snippit
-(void) retriveData
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://www.fr20.wearedesigners.net/WADMac/tourism/fetchGuideListAndroid.php"
parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.posts =(NSDictionary *)responseObject;
self.post =self.posts[#"thumbnail"];
NSLog(#"JSON: %#", self.post);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Please log into internetet"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
}
You are getting the response and the only problem i see is you are not able to retrieve values correctly.
While fetching data from JSON remember that in which format you are getting the data i.e. either you are getting arrays or dictionary.
Seeing your response you are getting Array which in itself contains dictionary.
use the below code to fetch the values
NSArray *array = [responseObject valueForKey:#"Main"];
for (NSDictionary *dict in array) {
NSInteger ids = [[dict valueForKey:#"id"] integerValue];
NSString *name = [dict valueForKey:#"name"];
NSString *thumbnail = [dict valueForKey:#"thumbnail"];
NSArray *arrImages = [dict valueForKey:#"images"];
//You can use them accordingly
}
Hope this helps you. Happy coding :)
Related
this is my json content.
[
{
"sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
"commit":{
"author":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"committer":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"message":"Merge branch '1.5.x'",
}
}
]
and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.
NSMutableArray *CommitArray = [[NSMutableArray alloc] init];
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
commitDictObj.message = [CommitDictionary objectForKey:#"message"];
for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:#"committer"]) {
Committer *author = [[Committer alloc] init];
author.name = [CommitterDictionary objectForKey:#"name"];
author.email = [CommitterDictionary objectForKey:#"email"];
author.date = [CommitterDictionary objectForKey:#"date"];
}
[CommitArray addObject:commitDictObj];
}
for (int i =0 ; i < [CommitArray count] ; i++){
CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
NSLog(#"Commit Message: %#", commitDictObj.message);
}
return 0;
}
}
i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?
Your array contains a dictionary, and that dictionary contains the commit dictionary, not the commit dictionary directly. Replace that part of your code:
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
With that:
for (NSDictionary *shaCommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
NSDictionary *CommitDictionary = [shaCommitDictionary objectForKey:#"commit"];
(1) Convert JSON to NSDictionary
NSData *jsonData= ... // Assume you got the data already loaded
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
(2) Access the dictionary values (fast enumeration available by now!!
NSString *message = dictionary[#"message"];
NSDictionary *author = dictionary[#"author"];
NSString *name = author[#"author"];
NSString *email = author[#"author"];
NSString *date = author[#"author"];
// OR:
// NSString *name = dictionary[#"author"][#"author"];
// NSString *email = dictionary[#"author"][#"author"];
// NSString *date = dictionary[#"author"][#"author"];
And thats it. I think the tricky thing is to get the JSON Data to the NSDictionary?
See here: https://stackoverflow.com/a/30561781/464016
I am calling the graph api to retrieve my user's events.And I get back an NSDictionary response. My problem is that I'm trying to access the names of the events but can't figure out the correct way of doing it. Can you please help me with this?
My response :
events = {
data = (
{
id = 16245704637388667;
name = "My event name";
place = {
id = 278379712223737;
location = {
city = Beijing;
country = China;
latitude = "53.598408783333";
....
Mycode to retrieve the vent name:
if ([result objectForKey:#"data"]){
NSArray *events = [result objectForKey:#"data"];
NSString *text=#"You don't have events!";
for (NSDictionary* myevent in events) {
NSString *myeventName = [myevent objectForKey:#"name"];
NSLog(#"%#",myeventName);
}
}
Found a solution:
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me/events" parameters: #{#"fields": #"name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSMutableArray* events = [result objectForKey:#"data"];
events names = [events valueForKey:#"name"];
}
}];`
I am trying to download google calendar data.
I am following a tutorial this link according to which implementing some of the GoogleOAuth delegate methods will let me get my desired data.
First I converted the response JSON data into an NSDictionary object and after that, I, NSLog this dictionary, to see the way the returned data is formed which is as shown below.
calendarInfoDict is {
etag = "\"1436255371893000\"";
items = (
{
accessRole = owner;
backgroundColor = "#9a9cff";
colorId = 17;
defaultReminders = (
{
method = popup;
minutes = 30;
}
);
etag = "\"1436255371893000\"";
foregroundColor = "#000000";
id = "sabiranthapa#gmail.com";
kind = "calendar#calendarListEntry";
notificationSettings = {
notifications = (
{
method = email;
type = eventCreation;
},
{
method = email;
type = eventChange;
},
{
method = email;
type = eventCancellation;
},
{
method = email;
type = eventResponse;
}
);
};
primary = 1;
selected = 1;
summary = "sabiranthapa#gmail.com";
timeZone = "Asia/Calcutta";
},
{
accessRole = reader;
backgroundColor = "#92e1c0";
colorId = 13;
defaultReminders = (
);
description = "Displays birthdays of people in Google Contacts and optionally \"Your Circles\" from Google+. Also displays anniversary and other event dates from Google Contacts, if applicable.";
etag = "\"1436255358367000\"";
foregroundColor = "#000000";
id = "#contacts#group.v.calendar.google.com";
kind = "calendar#calendarListEntry";
summary = Birthdays;
timeZone = "Asia/Calcutta";
}
);
kind = "calendar#calendarList";
nextSyncToken = 00001436255371893000;
}
According to tutorial there is a block containing a bunch of information regarding every calendar I have created in Google Calendars inside curly bracket. But I am not getting any events that I have saved which can be seen in Google Calendar after signing in gmail but not in my apps where I need to work with it.
My code is
-(void)responseFromServiceWasReceived:(NSString *)responseJSONAsString andResponseJSONAsData:(NSData *)responseJSONAsData{
NSError *error;
if ([responseJSONAsString rangeOfString:#"calendarList"].location != NSNotFound) {
NSDictionary *calendarInfoDict = [NSJSONSerialization JSONObjectWithData:responseJSONAsData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"calendarInfoDict is %#", calendarInfoDict);
if (error) {
NSLog(#"%#", [error localizedDescription]);
}
else{
NSArray *calendarsInfo = [calendarInfoDict objectForKey:#"items"];
if (_arrGoogleCalendars == nil) {
_arrGoogleCalendars = [[NSMutableArray alloc] init];
}
for (int i=0; i<[calendarsInfo count]; i++) {
NSDictionary *currentCalDict = [calendarsInfo objectAtIndex:i];
NSArray *values = [NSArray arrayWithObjects:[currentCalDict objectForKey:#"id"],
[currentCalDict objectForKey:#"summary"],
nil]; NSArray *keys = [NSArray arrayWithObjects:#"id", #"summary", nil];
[_arrGoogleCalendars addObject:
[[NSMutableDictionary alloc] initWithObjects:values forKeys:keys]];
}
_dictCurrentCalendar = [[NSDictionary alloc] initWithDictionary:[_arrGoogleCalendars objectAtIndex:0]];
[_barItemPost setEnabled:YES];
[_barItemRevokeAccess setEnabled:YES];
[self showOrHideActivityIndicatorView];
But I always end up with condition
if (_arrGoogleCalendars == nil) {
_arrGoogleCalendars = [[NSMutableArray alloc] init];
}
without able to access my events.
How can I download (or access) my Events from google calendar?
I have a NSArray which is based on JSON format. I requested it from the web and saved it in the array. I am trying to use a dictionary to get the values of "categoryname" and "subscore" and store them in new arrays, but they remain empty. Do I have to convert the array back to NSData using JSON serialisation or is there a more direct way to achieve this?
NSArray detailedscore:
{
"articles": [
{
"abstract": "text",
"title": "title"
}
],
"subscore": 3,
"categoryname": "Reporting"
},
{
"articles": [
{
"abstract": "text2",
"title": "title"
}
],
"subscore": 1,
"categoryname": "Power"
}]
}
Code:
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores addObject:subscore];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
{} ----> means dictionary, []---> array..... this is a rule I follow while assinging the return value from webservices as NSArray or NSDictionary....
Depending on your current JSON format, perhaps this might give you an idea
NSMutableArray *categoryArray = [NSMutableArray new];
for (NSDictionary *childDict in self.detailedscore)
{
[categoryArray addObject:[childDict objectForkey:#"categoryname"]];
}
If you have the array use below code
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores score];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
The problem wasn't in the array or dictionary or the web request. I didn't allocated the NSMutableArrays so they were empty all the time. The code works fine for extracting values from the array in case anyone wants to use it.
Hope this helps.
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&connectionError];
NSLog(#"Dict %#",dict);
BOOL isValid = [NSJSONSerialization isValidJSONObject:dict];
if (isValid) {
[target getJSONFromresponseDictionary:dict forConnection:strTag error:connectionError];
}
else{
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[target getStringFromresponseDictionary:strResponse forConnection:strTag error:error];
}
I have a view that has tableviewcells on it, loaded with different "key values" as the label. When I tap on one I open another view. However here, I pass the dictionary for just that key, for example I would pass this:
{
key = Budget;
value = {
"2012 Budget Report" = {
active = 0;
author = "xxxxx xxxxxx";
date = "October 27, 2012";
description = "Example";
dl = "53 downloads";
email = "xxx#xxxxx.com";
ext = DOCX;
fortest = "Tuesday, November 6";
id = 5;
subject = budget;
testdate = "Tuesday, November 6";
title = "Budget spreadSheet";
};
"2005 - 2008 Budget Report" = {
active = 0;
author = "xxxxxxx xxxxx";
date = "November 3, 2012";
description = "Example";
dl = "18 downloads";
email = "xxxxx#xxxxx.com";
ext = DOCX;
title = "Budget report";
};
};
}
How do I get each of these values? Thanks.
Please note: the titles in value array are subject to change... More could be added, one could be deleted, so I need a general solution.
Considering the dictionary you passed is saved in iDictionary.
NSDictionary *iDictionary // Input Dictionary;
NSDictionary *theValues = [NSDictionary dictionaryWithDictionary:[iDictionary valueForKey:#"value"]];
for (NSString *aKey in [theValues allKeys]) {
NSDictionary *aValue = [theValues valueForKey:aKey];
NSLog(#"Key : %#", aKey);
NSLog(#"Value : %#", aValue);
// Extract individual values
NSLog(#"Author : %#", [aValue objectForKey:#"author"]);
// If the titles are dynamic
for (NSString *aSubKey in [aValue allKeys]) {
NSString *aSubValue = [aValue objectForKey:aSubKey];
NSLog(#"SubKey : %#, SubValue = %#", aSubKey, aSubValue);
}
}
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSArray *arrBudget= [jsonDictionary objectForKey:#"Budget"];
So here arrBudget will contain All the values And you can Pass the array to detail view.
Another approach if keys and objects are useful in the "foreach" logic :
NSDictionary *dict = #{
#"key1": #"value1",
#"key2": #"value2",
#"key3": #"value3",
};
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(#"Your key : %#", key);
NSLog(#"Your value : %#", [obj description]);
// do something...
}];