client server json response - ios

I need to display particular object for key(currency) using post method after getting response from web.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController{
NSMutableData *mutableData;
NSMutableString *arr;
#define URL #"website"
// change this URL
#define NO_CONNECTION #"No Connection"
#define NO_VALUES #"Please enter parameter values"
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)sendDataUsingPost:(id)sender{
[self sendDataToServer :#"POST"];
}
-(IBAction)sendDataUsingGet:(id)sender{
[self sendDataToServer : #"GET"];
}
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid=#"3";
serverResponse.text = #"Getting response from server...";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
NSLog(#"responseData: %#", arr);
//NSLog(#"%#",[[arr valueForKey:#"BranchByList"]objectForKey:#"currency"]);
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
if( connection )
{
mutableData = [NSMutableData new];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
serverResponse.text = NO_CONNECTION;
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableString *responseStringWithEncoded = [[NSMutableString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
//NSLog(#"Response from Server : %#", responseStringWithEncoded);
NSLog(#"%#",responseStringWithEncoded );
NSLog(#"%#",[responseStringWithEncoded valueForKeyPath:#"BranchByList.currency"] );
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
// NSLog(#"%#",attrStr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
i got response branch_id=3 but i want to show to "currency" but i tried lot but failure.
my response like this I need to display only currency.....
Response from Server :
{"BranchByList":
[
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newant‌​ara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
},
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/i‌​mages\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
}
]};

Your response structure is:
-Dictionary
--Array
---Dictionary Objects
You need to convert your Data into NSDictionary to parse it.
Following code will do that for you:
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error]; //Now we got top level dictionary
NSArray* responseArray = [json objectForKey:#"BranchByList"]; //Now we got mid level response array
//Get Embeded objects from response Array:
NSDictionary *priceDic = [responseArray objectAtIndex:0]; //Getting first object since you arent telling what the second object is for
NSString *buyingPrice = [priceDic objectForKey: #"buy"]; //Buying price
NSString *sellingPrice = [priceDic objectForKey:#"sell"]; //Selling price
NSString *currency = [priceDic objectForKey:#"currency"]; //Currency
Though this is only sticking to the point and getting the job done.
Proper way to get the job done would be to create a model class for response. Create a class inherited from NSObject and use it as model for this response. Add a initWithDic: method to that class, Pass it your response dic as parameter and delegate all this dictionary parsing to that method.
Also, NSURLConnection is deprecated since iOS 9.0. You should use NSURLSession instead.

Try This May be it will help you:-
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMArray *array1 = [dict6 objectForKey:#"BranchByList"];
NSLog(#"DICT : %#",array1);
NSDictionary *Dict3 = [array1 objectAtIndex:0];
NSString *Str1 = [dict3 objectForKey:#"currency"];
NSLog(#"Str1 : %#",Str1);
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
} else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
} else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
} else
{
return jsonObject;
}
}

Related

How to add Events from web service on calendar in Objective C

I am new in iOS and I am facing problem regarding to show events on calendar.I am using JTCalendar
https://github.com/chu888chu888/IOS-JTCalendar
My code is like this
In viewDidLoad
_calendarManager = [JTCalendarManager new];
_calendarManager.delegate = self;
// Generate random events sort by date using a dateformatter for the demonstration
//[self createRandomEvents];
// Create a min and max date for limit the calendar, optional
[self createMinAndMaxDate];
[_calendarManager setMenuView:_calendarMenuView];
[_calendarManager setContentView:_calendarContentView];
[_calendarManager setDate:_todayDate];
#pragma mark - CalendarManager delegate
// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
// Today
if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor blueColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Selected date
else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor redColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Other month
else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor lightGrayColor];
}
// Another day of the current month
else{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor blackColor];
}
if([self haveEventForDay:dayView.date]){
dayView.dotView.hidden = NO;
}
else{
dayView.dotView.hidden = YES;
}
}
- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
_dateSelected = dayView.date;
// Animation for the circleView
dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
[UIView transitionWithView:dayView
duration:.3
options:0
animations:^{
dayView.circleView.transform = CGAffineTransformIdentity;
[_calendarManager reload];
} completion:nil];
// Don't change page in week mode because block the selection of days in first and last weeks of the month
if(_calendarManager.settings.weekModeEnabled){
return;
}
// Load the previous or next page if touch a day from another month
if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
[_calendarContentView loadNextPageWithAnimation];
}
else{
[_calendarContentView loadPreviousPageWithAnimation];
}
}
}
#pragma mark - CalendarManager delegate - Page mangement
// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}
- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar
{
// NSLog(#"Next page loaded");
}
- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar
{
// NSLog(#"Previous page loaded");
}
#pragma mark - Fake data
- (void)createMinAndMaxDate
{
_todayDate = [NSDate date];
// Min date will be 2 month before today
_minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-12];
// Max date will be 2 month after today
_maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:12];
}
// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter;
if(!dateFormatter){
dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"dd-MM-yyyy";
}
return dateFormatter;
}
- (BOOL)haveEventForDay:(NSDate *)date
{
NSString *key = [[self dateFormatter] stringFromDate:date];
if(_eventsByDate[key] && [_eventsByDate[key] count] > 0){
return YES;
}
return NO;
}
//- (void)createRandomEvents
//{
// _eventsByDate = [NSMutableDictionary new];
//
// for(int i = 0; i < 30; ++i){
// // Generate 30 random dates between now and 60 days later
// NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
//
// // Use the date as key for eventsByDate
// NSString *key = [[self dateFormatter] stringFromDate:randomDate];
//
// if(!_eventsByDate[key]){
// _eventsByDate[key] = [NSMutableArray new];
// }
//
// [_eventsByDate[key] addObject:randomDate];
// }
//}
Its output is like this 02/06/2017 in array.How can I show it on calendar.
It is showing random events.But how can I show events on date?
Thanks in Advance!
Web Service
Getting value from 3 web service
#pragma mark - Schedule Audit Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleAudit{
[customActivityIndicator startAnimating];
int Auditid =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<Get_Audits_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Audits_Schedules_User>"
"</soap:Body>"
"</soap:Envelope>",Auditid];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
// NSURLRequest *myNSURequestObj=[NSURLRequest requestWithURL:myNSUObj];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/Get_Audits_Schedules_User" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleAudit=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleAudit);
if(myNSUConnectionObjScheduleAudit)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleAudit=[[NSMutableData alloc]init];
}
}
#pragma mark - Schedule Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleMeeting{
int KPI =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<Get_Kpi_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Kpi_Schedules_User>"
"</soap:Body>"
"</soap:Envelope>",KPI];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
// NSURLRequest *myNSURequestObj=[NSURLRequest requestWithURL:myNSUObj];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/Get_Kpi_Schedules_User" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleKPI=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleKPI);
if(myNSUConnectionObjScheduleKPI)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleKPI=[[NSMutableData alloc]init];
}
}
#pragma mark - Schedule Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleKPI{
int KPI =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<Get_Meeting_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Meeting_Schedules_User>"
"</soap:Body>"
"</soap:Envelope>",KPI];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
// NSURLRequest *myNSURequestObj=[NSURLRequest requestWithURL:myNSUObj];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/Get_Meeting_Schedules_User" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleMeeting=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleMeeting);
if(myNSUConnectionObjScheduleMeeting)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleMeeting=[[NSMutableData alloc]init];
}
}
#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if(connection == myNSUConnectionObjScheduleAudit)
{
[myNSMDataFromServerScheduleAudit setLength:0];
}
if(connection == myNSUConnectionObjScheduleKPI)
{
[myNSMDataFromServerScheduleKPI setLength:0];
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
[myNSMDataFromServerScheduleMeeting setLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if(connection == myNSUConnectionObjScheduleAudit)
{
[myNSMDataFromServerScheduleAudit appendData:data];
}
if(connection == myNSUConnectionObjScheduleKPI)
{
[myNSMDataFromServerScheduleKPI appendData:data];
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
[myNSMDataFromServerScheduleMeeting appendData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if(connection == myNSUConnectionObjScheduleAudit)
{
loginStatusScheduleAudit = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleAudit mutableBytes] length:[myNSMDataFromServerScheduleAudit length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleAudit);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleAudit error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleAudit = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleAudit);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Audits_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Audits_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleAudit = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
EndDatearrayScheduleAudit =[[NSMutableArray alloc] init];
EndDatearrayScheduleAudit=[responsedictScheduleAudit valueForKey:#"EndDate"];
}
}
if(connection == myNSUConnectionObjScheduleKPI)
{
loginStatusScheduleKPI = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleKPI mutableBytes] length:[myNSMDataFromServerScheduleKPI length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleKPI);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleKPI error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleKPI = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleKPI);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Kpi_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Kpi_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleKPI = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
EndDatearrayScheduleKPI =[[NSMutableArray alloc] init];
EndDatearrayScheduleKPI =[responsedictScheduleKPI valueForKey:#"EndDate"];
}
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
loginStatusScheduleMeeting = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleMeeting mutableBytes] length:[myNSMDataFromServerScheduleMeeting length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleMeeting);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleMeeting error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleMeeting = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleMeeting);
NSDictionary* AddressDict=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",AddressDict);
NSDictionary *new =[AddressDict objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Meeting_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Meeting_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleMeeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
EndDatearrayScheduleMeeting =[[NSMutableArray alloc] init];
EndDatearrayScheduleMeeting =[responsedictScheduleMeeting valueForKey:#"EndDate"];
}
}
[customActivityIndicator stopAnimating];
}
#pragma mark - NSXMLParsing Delegate
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"FillBlocksNew"])
{
myDataClassObjScheduleAudit=[[mydata alloc]init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
myMutableStringObjScheduleAudit=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleAudit);
NSData *dataAudit = [myMutableStringObjScheduleAudit dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleAudit = [NSJSONSerialization JSONObjectWithData:dataAudit options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleAudit);
myMutableStringObjScheduleKPI=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleKPI);
NSData *dataKPI = [myMutableStringObjScheduleKPI dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleKPI = [NSJSONSerialization JSONObjectWithData:dataKPI options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleKPI);
myMutableStringObjScheduleMeeting=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleMeeting);
NSData *dataMeeting = [myMutableStringObjScheduleMeeting dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleMeeting = [NSJSONSerialization JSONObjectWithData:dataMeeting options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleMeeting);
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(#"DataArray: %#",myDataNSMArrayScheduleAudit);
}
You have commented function "createRandomEvents" in your source code.
This function defines your dates to be displayed on calendar.
Get events data from web service and you have to add dates in array "eventsByDate". Then you should be able to view dates.
Code:
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *arrDates = [[NSMutableArray alloc] init];
}
In ScheduleKPI API response
[arrDates addObjectsFromArray:EndDatearrayScheduleKPI];
In ScheduleAudit API response
[arrDates addObjectsFromArray:EndDatearrayScheduleAudit];
In ScheduleMeeting API response
[arrDates addObjectsFromArray:EndDatearrayScheduleMeeting];
[self funAddEvents:arrDates];
- (void)funAddEvents:(NSArray *)arrDate
{
eventsByDate = [NSMutableDictionary new];
for(NSString *strDate in arrDate){
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:#"YYYY/MM/dd"];
NSDate *myDate = [dateformat dateFromString:strDate];
NSString *key = [[self dateFormatter] stringFromDate:myDate];
if(!eventsByDate[key]){
eventsByDate[key] = [NSMutableArray new];
}
[eventsByDate[key] addObject:myDate];
}
[self.calendar reloadData];
}

Encode NSDictionary to send across AFNetworking

How can i URLEncode a NSDictionary so i can send it across AFNetworking.
The code is as follows:
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
How can i Encode this NSDictionary so i can send it across AFNetworking ?
Depends how you wish to send your data:
1) #"application/json" in which case you would use [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]
2) #"application/x-www-form-urlencoded" in which case you basically want to create the string: ?id=1211&man=33 from your dictionary rus.
Here's some code, may not be the most efficient by you get the idea:
NSString *temp;
int i=0;
for(NSString *key in options.params.allKeys)
{
NSString *value = [options.params objectForKey:key];
[parameters setObject:value forKey:key];
if(i==0)
{
temp = [NSString stringWithFormat:#"?%#=%#", key,value];
}
else
{
temp = [NSString stringWithFormat:#"%#&%#=%#", temp, key, value];
}
}
Note: may or may not be relevant to you, but my two cents:
I use AFHTTPSessionManager which handles all the details for me including url encoding, so I just pass in the desired dictionary:
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
[self POST:#"/api/place/nearbysearch" parameters:rus success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"nearbyPlaces: success");
[self fetchedPlacesData:responseObject block:block];
if(task != nil && task.originalRequest != nil)
{
NSString *url = [task.originalRequest.URL absoluteString];
[self saveNearbySearchEvent:url params:params];
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"nearbyPlaces: error: %#", error);
block(self, nil, error);
}];
AFHTTPSessionManager encapsulates a lot of functionality included serializing the data: AFURLRequestSerialization either as JSON or HTTP Request. In case you interested on what AFHTTPSessionManager actually does here's some detail:
A) HTTP Request
Here's the code from AFURLRequestSerialization.m:
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
NSString *query = nil;
if (self.queryStringSerialization) {
NSError *serializationError;
query = self.queryStringSerialization(request, parameters, &serializationError);
if (serializationError) {
if (error) {
*error = serializationError;
}
return nil;
}
} else {
switch (self.queryStringSerializationStyle) {
case AFHTTPRequestQueryStringDefaultStyle:
query = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding);
break;
}
}
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? #"&%#" : #"?%#", query]];
} else {
if (![mutableRequest valueForHTTPHeaderField:#"Content-Type"]) {
[mutableRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
}
[mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
}
}
return mutableRequest;
}
B) JSON
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:#"Content-Type"]) {
[mutableRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
}
[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
}
return mutableRequest;
}
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:#"1211" forKey:#"id"];
[rus setValue:#"33" forKey:#"man"];
If you are exchanging JSON data with your server:
NSError *error = nil;
NSData *aRequestData = [NSJSONSerialization dataWithJSONObject:rus options:NSJSONWritingPrettyPrinted error:&error];
if (!error) {
[urlRequest setHTTPBody:aRequestData];
}
If you are exchanging PLIST data with your server:
[self stringByAppendingQueryParameters:rus appendQuestionMark:NO];
- (NSString *)stringByAppendingQueryParameters:(NSDictionary *)iParameters appendQuestionMark:(BOOL)iAppendQuestionMark {
BOOL aAppendAmpersand = YES;
NSMutableString *aWorking = [NSMutableString stringWithString:self];
if (iAppendQuestionMark) {
NSRange aQueryBeginning = [self rangeOfString:#"?"];
if (aQueryBeginning.location == NSNotFound) {
[aWorking appendString:#"?"];
aAppendAmpersand = NO;
}
} else {
aAppendAmpersand = NO;
}
for (id aKey in iParameters) {
id aValue = [iParameters valueForKey:aKey];
NSString *aKeyStr = [self convertObjectToURLEncodedValue:aKey];
if (aAppendAmpersand) {
[aWorking appendString:#"&"];
} else {
aAppendAmpersand = YES;
}
if ([aValue isKindOfClass:[NSArray class]]) {
NSArray *aSubParamaters = (NSArray *)aValue;
BOOL aFirstTime = YES;
for (id aSubValue in aSubParamaters) {
NSString *aValueString = [self convertObjectToURLEncodedValue:aSubValue];
if (!aFirstTime) {
[aWorking appendString:#"&"];
}
[aWorking appendString:aKeyStr];
[aWorking appendString:#"="];
[aWorking appendString:aValueString];
aFirstTime = NO;
}
} else {
NSString *aValueString = [self convertObjectToURLEncodedValue:aValue];
[aWorking appendString:aKeyStr];
[aWorking appendString:#"="];
[aWorking appendString:aValueString];
}
}
return [NSString stringWithString:aWorking];
}
- (NSString *)convertObjectToURLEncodedValue:(id)iObject {
NSString *anIntermediate = nil;
if ([iObject isKindOfClass:[NSString class]]) {
anIntermediate = iObject;
} else if ([iObject respondsToSelector:#selector(stringValue)]) {
anIntermediate = [iObject stringValue];
} else {
anIntermediate = [iObject description];
}
NSString *anEncodingString = (__bridge_transfer NSString *)(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef)anIntermediate,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 ));
return anEncodingString;
}

Add Several NSStrings to NSMutableArray

I have an API GET Request that runs multiple times using a for loop. I am successfully able to create some NSStrings from this, but given that the loop, I need a good way to store it all together. So, at the end of the connectionRequest, I have it run another method, where I add the NSString to an NSMutableArray. However, when I check the contents of the NSMutableArray, it's only the most recent NSString in there. What am I missing?
- (void)viewWillAppear:(BOOL)animated {
for(int i = 0; i< self.theNumber; i++) {
[self getQuote];
}
}
-(void) getQuote {
NSString *bringitalltogether = #"URLOFAPI";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:bringitalltogether]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableDictionary *allResults = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
NSArray *book = [allResults valueForKey:#"bookname"];
self.bookstring = [book objectAtIndex:0];
NSArray *chapter = [allResults valueForKey:#"chapter"];
self.chapterstring = [chapter objectAtIndex:0];
NSArray *verse = [allResults valueForKey:#"verse"];
self.versestring = [verse objectAtIndex:0];
NSArray *text = [allResults valueForKey:#"text"];
self.textstring = [text objectAtIndex:0];
[self doneGotIt];
}
- (void) doneGotIt {
self.theArray = [[NSMutableArray alloc] init];
NSString *doIt = [NSString stringWithFormat:#"%# - %# %#:%#", self.textstring, self.bookstring, self.chapterstring, self.versestring];
[self.theArray addObject:doIt];
NSLog(#"%#", self.theArray);
}
The console shows the NSLog running the appropriate number of times, but each time, the array stays with just one verse, when I would expect it to gradually grow.
You are creating the new array instance every time. thats y , u are getting the last part.
- (void) doneGotIt {
//Create array only once if not yet created in memory
if (!self.theArray) {
self.theArray = [[NSMutableArray alloc] init];
}
NSString *doIt = [NSString stringWithFormat:#"%# - %# %#:%#", self.textstring, self.bookstring, self.chapterstring, self.versestring];
[self.theArray addObject:doIt];
NSLog(#"%#", self.theArray);
}

Adding Multiple GET Requests to NSMutableArray in iOS App

The app keeps score during a game. Based off of your score, it will retrieve a quote from an online database, using a GET method and returning it in JSON format. For example, your score is 5, you get 1 quote, 10, you get 2 and so on. The view that shows the quote(s) is a UIViewController with a UITextView in it.
I have a for loop that runs based off the score, to run the same GET request over and over again, after a 1.5 second delay so the server housing the database won't reject requests made nearly simultaneously.
I create a few NSStrings and pull information from the JSON data, append it into some basic HTML code and then set that as the UITextView attributedText.
Most of the time this runs great, but every once in a while, I'll expect 2 quotes, and only get 1, or some of the quotes will wind up being the same.
Can someone tell me if there is a better way to go about doing this than how I currently am?
- (void)viewWillAppear:(BOOL)animated {
if ([textView.text isEqualToString:#""]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger getReady = [defaults integerForKey:#"after"];
self.theNumber = getReady;
for(int i = 0; i< self.theNumber; i++) {
[self performSelector:#selector(quoteView) withObject:self afterDelay:1.5 ];
}
}
}
-(void) quoteView {
NSString *bringitalltogether = #"http://url.com&type=json";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:bringitalltogether]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
if (code == 200){
}
else
{
UIAlertView *oops = [[UIAlertView alloc] initWithTitle:#"Oops" message:#"The network is having difficulties getting you the quote. Please check your network settings and try again later." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[oops show];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableDictionary *allResults = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
NSArray *book = [allResults valueForKey:#"bookname"];
self.bookstring = [book objectAtIndex:0];
NSArray *chapter = [allResults valueForKey:#"chapter"];
self.chapterstring = [chapter objectAtIndex:0];
NSArray *verse = [allResults valueForKey:#"verse"];
self.versestring = [verse objectAtIndex:0];
NSArray *text = [allResults valueForKey:#"text"];
self.textstring = [text objectAtIndex:0];
[self doneGotIt];
}
- (void) doneGotIt {
if (!self.theArray) {
self.theArray = [[NSMutableArray alloc] init];
}
NSString *doIt = [NSString stringWithFormat:#"%# - %# %#:%#", self.textstring, self.bookstring, self.chapterstring, self.versestring];
[self.theArray addObject:doIt];
NSString *theEnd = [self.theArray componentsJoinedByString:#"\n"];
NSString *loadHTML = [#"<head> <style type='text/css'>a > img {pointer-events: none;cursor: default;}</style></head><b><div align=\"left\"><font size=5>" stringByAppendingString:theEnd];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[loadHTML dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
textView.attributedText = attributedString;
NSLog(#"ARRAY: %#", self.theArray);
NSLog(#"String: %#", theEnd);
}
-(IBAction)finished {
[self dismissViewControllerAnimated:YES completion:nil];
textView = nil;
}
From the NSLogs I have towards the end there, sometimes the NSMutableArray contains several of the same quotes, which is why they don't show in the string, because it eliminates duplicates. My question is if there is a better way to do this that will keep these errors from occurring?
Here is some pseudo code for you
mutableArray = new NSMutableArray
while([mutableArray count] < total) {
quote = getQuote()
if([array indexOfObject:quote] != NSNotFound)
[mutableArray addObject:quote]
}
This will ensure you do not have duplicate quotes. After you have an array of valid quotes, you can then construct the string exactly how you want it.

Get back data after Json parsing

In my iOS app I've to parse a JSON file. From this JSON I need the following stuff: name, image width and image height. To get image name I'ven't any problem, to get image with and height I use the following code:
- (void) loadImageFromWeb:(NSString *)urlImg forName:(NSString*)name {
NSURL* url = [NSURL URLWithString:urlImg];
//NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *authCredentials =#"reply:reply";
NSString *authValue = [NSString stringWithFormat:#"Basic %#",[authCredentials base64EncodedStringWithWrapWidth:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:data];
imageWidth = image.size.width;
imageHeight = image.size.height;
imgWidth = [NSString stringWithFormat:#"%f", imageWidth];
imgHeight = [NSString stringWithFormat:#"%f", imageHeight];
self.dictWithDataForPSCollectionView = #{#"title": name,
#"width": imgWidth,
#"height": imgHeight};
[self.arrayWithData addObject:self.dictWithDataForPSCollectionView];
NSLog(#"DATA ARRAY: %#", self.arrayWithData);
} else {
NSLog(#"ERRORE: %#", error);
}
}];
}
You can see that I save the name, image width and image height in a NSDictionary then I put this in an NSMutableArray. When it execute the NSLog, I see this:
DATA ARRAY: (
{
height = "512.000000";
title = "Eau de Toilet";
width = "320.000000";
},
{
height = "1049.000000";
title = "Eau de Toilet";
width = "1405.000000";
}
)
My question is how to get this information back in the class who call my json parser, I tried to access to the variable in this way:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
recivedData = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[recivedData appendData:data];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", string);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *json;
NSError *err;
json = [NSJSONSerialization JSONObjectWithData:recivedData options:NSJSONReadingMutableLeaves error:&err];
JsonCategoryReader *reader = [[JsonCategoryReader alloc]init];
[reader parseJson:json];
}
But when I run the code it shows me an empty array. How I can have the information in this class?
UPDATE:
The JSON I've to parse is the following:
{
"1":{
"entity_id":"1",
"type_id":"simple",
"sku":"EAU_DE_TOILET_1",
"description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
"short_description":"EAU DE TOILETTE NATURAL SPRAY",
"meta_keyword":null,
"name":"Eau de Toilet",
"meta_title":null,
"meta_description":null,
"regular_price_with_tax":60,
"regular_price_without_tax":60,
"final_price_with_tax":60,
"final_price_without_tax":60,
"is_saleable":true,
"image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/p\/r\/product_100ml.png"
},
"2":{
"entity_id":"2",
"type_id":"simple",
"sku":"EAU_DE_TOILET_2",
"description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
"short_description":"EAU DE TOILETTE NATURAL SPRAY",
"meta_keyword":null,
"name":"Eau de Toilet",
"meta_title":null,
"meta_description":null,
"regular_price_with_tax":60,
"regular_price_without_tax":60,
"final_price_with_tax":60,
"final_price_without_tax":60,
"is_saleable":true,
"image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/s\/c\/scheda_non_shop.jpg"
}
}
My method parseJson do the following:
- (void)parseJson:(NSDictionary *)jsonDict {
// Controllo che il json sia stato ricevuto
if (jsonDict) {
self.nameArray = [[NSMutableArray alloc]init];
self.imgUrlArray = [[NSMutableArray alloc]init];
self.dictWithDataForPSCollectionView = [[NSDictionary alloc]init];
self.arrayWithData = [[NSMutableArray alloc]init];
[self createArrayWithJson:jsonDict andIndex:1];
[self createArrayWithJson:jsonDict andIndex:2];
}
- (void)createArrayWithJson:(NSDictionary*)json andIndex:(NSString*)i {
NSDictionary *products = [json objectForKey:i];
NSString *name = [products objectForKey:#"name"];
NSString *imgUrl = [products objectForKey:#"image_url"];
// Scarico l'immagine e calcolo le dimensioni
if (name != nil && imgUrl != nil) {
[self loadImageFromWeb:imgUrl forName:name];
}
}
I hope you understand what I did
what happen is that your class is make before that your json is download, for have a good sequence you have to call your method for parse the json inside the completionHandler block, when you are sure that it is download. then when you have your object load you can parse it like this example:
for (NSDictionary *dic in reader.arrayWithData){
NSLog("height: %#",[dic objectForKey:#"height"]);
NSLog("title: %#",[dic objectForKey:#"title"]);
NSLog("width: %#",[dic objectForKey:#"width"]);
}

Resources