NSString is coming nil - ios

I am new to iOS. Its my first app in which I am calling JSON date from server.
I have to store coming values in tabkeviewcell, but when I am setting value in NSString it is getting nil.
Below is my code :-
.h file
#interface SecondViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
#property (strong, nonatomic) IBOutlet UITableView *tableview;
#property(strong,nonatomic) NSMutableDictionary *jsonresponse;
#property(strong, nonatomic) NSMutableArray *jsonresultarr;
.m file
- (void)viewDidLoad {
[self retrievedata];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void) retrievedata
{
//NSMutableArray *jsonresultarr=[NSMutableArray new];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://magmasysdev.com/ddc/getAllCompanies.php"]]; // this is your request url
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err]; // here parsing the array
NSArray *firstArry=[[jsonArray objectAtIndex:1]objectForKey:#"company_data"];
for (int i=0; i<[firstArry count]; i++)
{
_jsonresponse= [firstArry objectAtIndex:i];
NSString *Company_Id=[_jsonresponse objectForKey:#"Company_Id"];
NSString *Company_Name=[_jsonresponse objectForKey:#"Company_Name"];
NSString *Company_Address=[_jsonresponse objectForKey:#"Company_Address"];
NSString *Company_Email=[_jsonresponse objectForKey:#"Company_Email"];
NSString *Company_Tel_Num=[_jsonresponse objectForKey:#"Company_Tel_Num"];
NSString *Company_Website=[_jsonresponse objectForKey:#"Company_Website"];
NSString *Company_Fax_Num=[_jsonresponse objectForKey:#"Company_Fax_Num"];
[_jsonresultarr addObject:Company_Id];
[_jsonresultarr addObject:Company_Name];
[_jsonresultarr addObject:Company_Address];
[_jsonresultarr addObject:Company_Email];
[_jsonresultarr addObject:Company_Tel_Num];
[_jsonresultarr addObject:Company_Website];
[_jsonresultarr addObject:Company_Fax_Num];
}
[_tableview reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(self.jsonresultarr) // coming nil
{ return _jsonresultarr.count;
}
return 7;
}
Here is my output response. Can anyone please give me an example or try to modify my code so that I can store data in text boxes.
[{"status":"Y"},{"company_data":[{"Company_Id":"5","Company_Name":"SANTE (PVT) LIMITED","Company_Address":"245\/2-Z P.E.C.H.S Block-6 \nKarachi-75400,Pakistan","Company_Email":"sante#sante.com.pk","Company_Tel_Num":"4520507, 4533425","Company_Website":"www.sante.com.pk","Company_Fax_Num":"4.54885e+006"}

as per your response of array , you get dictionary at index "1" for key "company_data".
NSDictionary *dict = [[innerObject objectAtIndex:1] objectForKey:#"company_data"];
NSString *strCompanyId = [dict objectForKey:#"Company_Id"];
NSString *strCompanyName = [dict objectForKey:#"Company_Name"];
NSString *strCompanyAddress = [dict objectForKey:#"Company_Address"];
NSString *strCompanyEmail = [dict objectForKey:#"Company_Email"];
NSString *strCompanyPhone = [dict objectForKey:#"Company_Tel_Num"];
NSString *strCompanySite = [dict objectForKey:#"Company_Website"];
NSString *strCompanyFax = [dict objectForKey:#"Company_Fax_Num"];
You can set appropriate textField with this strings!

NSMutableArray *jsonresultarr=[NSMutableArray new]; // declare this array in globally
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://magmasysdev.com/ddc/getAllCompanies.php"]]; // this is your request url
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err]; // here parsing the array
NSArray *firstArry=[[jsonArray objectAtIndex:1]objectForKey:#"company_data"];
for (int i=0; i<[firstArry count]; i++)
{
NSMutableDictionary *getjsonresponse= [firstArry objectAtIndex:i];
NSString *Company_Id=[getjsonresponse objectForKey:#"Company_Id"];
NSString *Company_Name=[getjsonresponse objectForKey:#"Company_Name"];
NSString *Company_Address=[getjsonresponse objectForKey:#"Company_Address"];
NSString *Company_Email=[getjsonresponse objectForKey:#"Company_Email"];
NSString *Company_Tel_Num=[getjsonresponse objectForKey:#"Company_Tel_Num"];
NSString *Company_Website=[getjsonresponse objectForKey:#"Company_Website"];
NSString *Company_Fax_Num=[getjsonresponse objectForKey:#"Company_Fax_Num"];
}
another choice
for (NSDictionary *tmp in firstArry)
{
NSMutableDictionary * itemshowdetails=[[NSMutableDictionary alloc]init];
[itemshowdetails setValue:[tmp objectForKey:#"Company_Id"] forKey:#"Company_Id"];
[itemshowdetails setValue:[tmp objectForKey:#"Company_Name"] forKey:#"Company_Name"];
[itemshowdetails setValue:[tmp objectForKey:#"Company_Address"] forKey:#"Company_Address"];
[itemshowdetails setValue:[tmp objectForKey:#"Company_Email"] forKey:#"Company_Email"];
[itemshowdetails setValue:[tmp objectForKey:#"Company_Tel_Num"] forKey:#"Company_Tel_Num"];
[itemshowdetails setValue:[tmp objectForKey:#"Company_Website"] forKey:#"Company_Website"];
[itemshowdetails setValue:[tmp objectForKey:#"Company_Fax_Num"] forKey:#"Company_Fax_Num"];
[jsonresultarr addObject:itemshowdetails];
}
in your retrieve
NSString *pass = [[jsonresultarr objectAtIndex:0] objectForKey:#"Company_Id"]; // here pass your index if already I know else call the line inside the for loop
#pragma mark - tablevie data source
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [jsonresultarr count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 0.01f;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
.....
// here pass your details
cell.Company_Id.text = [[jsonresultarr objectAtIndex:indexPath.row ] objectForKey:#"Company_Id"];
cell.Company_Name.text = [[jsonresultarr objectAtIndex:indexPath.row ] objectForKey:#"Company_Name"];
cell.Company_Address.text = [[jsonresultarr objectAtIndex:indexPath.row ] objectForKey:#"Company_Address"];
cell. Company_Email.text = [[jsonresultarr objectAtIndex:indexPath.row ] objectForKey:#"Company_Email"];
cell.Company_Tel_Num.text = [[jsonresultarr objectAtIndex:indexPath.row ] objectForKey:#"Company_Tel_Num"];
cell.Company_Website.text = [[jsonresultarr objectAtIndex:indexPath.row ] objectForKey:#"Company_Website"];
cell.Company_Fax_Num.text = [[jsonresultarr objectAtIndex:indexPath.row ] objectForKey:#"Company_Fax_Num"];
return cell;
}

-(void) retrievedata
{
NSURL *url=[NSURL URLWithString:#"http://magmasysdev.com/ddc/getAllCompanies.php"];
NSData *data=[NSData dataWithContentsOfURL:url];
jsonarray=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
// companyarray = [[NSMutableArray alloc]init];
NSMutableArray *innerObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; // plz check here data is not nil
NSDictionary *dicarr=[innerObject objectAtIndex:1];
NSArray *arrCom=[dicarr objectForKey:#"company_data"];
for (int i=0;i<arrCom.count; i++)
{
NSDictionary *dicSub =[arrCom objectAtIndex:i];
NSString *strId=[dicSub objectForKey:#"Company_Id"];
NSString *strAddress=[dicSub objectForKey:#"Company_Address"];
}
}

Related

Parsing json from array of array

I have the json data were within the first array I main category array with name "Response" within that I have parent category array with name "0" within which I have child category array with name "0" and here is my json format
{"Response":[{"menuname":"Jewellery","menuid":"1","0":[{"catname":"Rings","catid":"1","0":[{"scatname":"Engagement Rings","scatid":"4"},{"scatname":"Wedding Rings","scatid":"5"},{"scatname":"kk","scatid":"35"}]},{"catname":"Pendants","catid":"2","0":[{"scatname":"Office Wear","scatid":"8"}]},{"catname":"Bracelets","catid":"3","0":[{"scatname":"Studded","scatid":"9"}]},{"catname":"Earrings","catid":"6","0":[{"scatname":"Ethnic Jhumkas","scatid":"7"}]},{"catname":"Chain's","catid":"33","0":[]},{"catname":"Jewel","catid":"34","0":[]}]},{"menuname":"Collections","menuid":"2","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"Gold Coin","menuid":"3","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"OFF THE SHELF","menuid":"4","0":[{"catname":"testing from pixel","catid":"13","0":[]},{"catname":"New pixel","catid":"23","0":[]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]}]}
and I want to display in expandable tableview as below
Jewellery
Rings
Engagement Rings
Wedding Rings
kk
Pendants
Ofice Wear
Collections
Sound Of Love
Love bracelet
Colorful Affair
Passion ring
Here is the code I used in viewdidLoad
NSDictionary *pJson;
NSMutableString *postStr = [NSMutableString stringWithString:kURL];
[postStr appendString:[NSString stringWithFormat:#"?tag=%#&id=%#",kCategoryFilter,kPrecious]];
[postStr setString:[postStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:postStr]];
NSLog(#"%#",postStr);
[request setHTTPMethod:#"POST"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
NSURL *url = [NSURL URLWithString:postStr];
NSData *data = [NSData dataWithContentsOfURL:url];
pJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",pJson);
NSMutableArray *arr = [pJson objectForKey:#"Response"];
NSLog(#"%lu",(unsigned long)arr.count);
NSMutableDictionary *dict2 =[[NSMutableDictionary alloc]init];// [arr objectAtIndex:NSIndexPath.row];
[dict2 setObject:arr forKey:#"dictionary1"];
dict2 = [arr objectAtIndex:0];
NSArray *arr1 =[dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
NSUInteger y;
for (int i=0;i<arr.count;i++) {
NSString *ring_data = [[arr objectAtIndex:i]objectForKey:#"menuname"];
NSString *id_data = [[arr objectAtIndex:i]objectForKey:#"menuid"];
NSLog(#"AUTHOR: %#",ring_data);
NSLog(#"%#",id_data);
dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"menuname",id_data,#"menuId",nil];
[myObject addObject:dictionary];
NSMutableArray *arr1 = [dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
y = arr.count;
for (NSUInteger i=0;i<arr1.count;i++) {
NSArray *count = [[[arr1 objectAtIndex:i] objectForKey:arr]valueForKey:#"catname"];
NSString *myCount = [NSString stringWithFormat:#"%lu",(unsigned long)[count count]];
NSString *ring_data = [[arr1 objectAtIndex:i]objectForKey:#"catname"];
NSLog(#"AUTHOR: %#",ring_data);
// NSLog(#"%#",catname_data);
dictionary1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"catname",
nil];
[myObject1 addObject:dictionary1];
}
}
I tried some coding for you.Follow that code and customize where you want to add to array and where to set dictionary.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[jsonArray objectForKey:#"Response"];
for (int i=0;i<[array count];i++)
{
NSMutableDictionary *dict = [array objectAtIndex:i];
NSMutableArray *arrayDictValue = [dict valueForKey:[NSString stringWithFormat:#"%d",0]];
NSString *strMenuName = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuname"]];
NSString *strMenuID = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuid"]];
NSLog(#"The strMenuName is-%#",strMenuName);
NSLog(#"The strMenuID is-%#",strMenuID);
for (int j=0; j<[arrayDictValue count]; i++)
{
NSMutableDictionary *dictInside = [arrayDictValue objectAtIndex:j];
NSArray *arrayInsideDict = [dictInside valueForKey:#"0"];
for (int k =0; k<[arrayInsideDict count]; i++)
{
NSString *strCatName = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catname"]];
NSString *strCatID = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catid"]];
NSLog(#"The strCateName is-%#",strCatName);
NSLog(#"The strCatID is-%#",strCatID);
NSMutableDictionary *dictInArray = [[arrayInsideDict objectAtIndex:0] valueForKey:#"0"];
NSString *strSCatName = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatname"]];
NSString *strSCatID = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatid"]];
NSLog(#"the strSCatName is - %#",strSCatName);
NSLog(#"the strSCatID is - %#",strSCatID);
}
}
}

how to parsing data in JSON to tableview

I have a json http://vmg.hdvietpro.com/ztv/home and how to parsing data json in this link to table view. I try this code but i cant get data from json to my application.Thanks for help
Movies.h
#interface Movies : NSObject
#property (strong,nonatomic) NSString *moviesId;
#property (strong,nonatomic) NSString *text1;
#property (strong,nonatomic) NSString *thumbnail;
#pragma mark -
#pragma mark Class Methods
-(id)initWithMoviesName:(NSString *)cText1 andThumbnail:(NSString*) cThum andMoviesID:(NSString*) cID;
#end
Movies.m
#implementation Movies
#synthesize text1,moviesId,thumbnail;
-(id)initWithMoviesName:(NSString *)cText1 andThumbnail:(NSString*) cThum andMoviesID:(NSString *) cID{
self=[super init];
if (self) {
text1=cText1;
thumbnail=cThum;
moviesId=cID;
}
return self;
}
#end
TableViewController
#define getDataURL #"http://vmg.hdvietpro.com/ztv/home"
-(void) retrieveData{
NSURL *url=[NSURL URLWithString:getDataURL];
NSData *data=[NSData dataWithContentsOfURL:url];
jsonArray=[NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:nil];
moviesArray=[[NSMutableArray alloc] init];
for (int i=0; i<jsonArray.count; i++) {
NSString *cID=[[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString *cName=[[jsonArray objectAtIndex:i] objectForKey:#"text1"];
NSString *cThum=[[jsonArray objectAtIndex:i] objectForKey:#"thumbnail"];
[moviesArray addObject:[[Movies alloc]initWithMoviesName:cName andThumbnail:cThum andMoviesID:cID]];
}
[self.tableView reloadData];
}
Try Following:
NSArray * respArray = [[[[json objectForKey:#"response"]objectForKey:#"hot_program"]objectForKey:#"itemPage"]objectForKey:#"page"];
Try doing something like this. This is not the exact solution and you'll have to work around your way.
NSString *link = [NSString stringWithFormat:#"yourServiceURL"];
NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encdLink];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
Now you have your data in the array and extract it out using objectForKey or valueForKey.
This is what I am doing to fetch images from JSON and showing in my app. Firstly get the array from the above code. Then extract out the image content like this :
_demoArray = [json valueForKey:#"ContentImage"];
Now you have the values in your demoArray.
Hope this helps.
I thing it's useful for you.try this way
#import "ViewController.h"
#interface ViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[self TableView]setDataSource:self];
array=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"https://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSLog(#"https://itunes.apple.com/us/rss/topaudiobooks/limit=10/json");
NSURLRequest *req=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:req delegate:self];
if(connection)
{
NSLog(#"Connected");
webData=[[NSMutableData alloc]init];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error is");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *all=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
// NSString *label=[all objectForKey:#"lable" ];
// [array addObject:label];
NSDictionary *feed=[all objectForKey:#"feed"];
NSArray *arrayOFEntry=[feed objectForKey:#"entry"];
for (NSDictionary *diction in arrayOFEntry) {
NSDictionary *title=[diction objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}NSLog(#"good mrng");
[[self TableView]reloadData];
}
- (IBAction)getTopMoves:(id)sender
{
NSLog(#"good mrng");
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
return cell;
}
#end
try this...
-(void) retrieveData1
{
NSURL * url = [NSURL URLWithString:getDataURL1];
NSData * data = [NSData dataWithContentsOfURL:url];
id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
_moviesArray=[[NSMutableArray alloc] init];
_moviesArray1=[[NSMutableArray alloc] init];
_moviesArray2=[[NSMutableArray alloc] init];
// NSArray * respArray = [[[[json objectForKey:#"response"]objectForKey:#"hot_program"]objectForKey:#"itemPage"]objectForKey:#"page"];
NSDictionary *dic=[json objectForKey:#"response"];
NSDictionary *dic1= [dic objectForKey:#"hot_program"];
NSDictionary *dic2=[dic1 objectForKey:#"itemPage"];
for (NSDictionary *diccc in [dic2 objectForKey:#"page"])
{
NSLog(#"%#",diccc);
[self.moviesArray addObject:[diccc objectForKey:#"id"]];
[self.moviesArray1 addObject:[diccc objectForKey:#"text1"]];
[self.moviesArray2 addObject:[diccc objectForKey:#"thumbnail"]];
}
NSLog(#"%#",self.moviesArray);
NSLog(#"%#",self.moviesArray1);
NSLog(#"%#",self.moviesArray2);
// [self.tableView reloadData];
}
it is one of way to parse a data there is lot of way to parse..
NSArray * respArray = [[[[json objectForKey:#"response"]objectForKey:#"hot_program"]objectForKey:#"itemPage"]objectForKey:#"page"];
NSLog(#"%#",respArray);
NSArray *respArray1= [[[[json objectForKey:#"response"]objectForKey:#"new_video"]objectForKey:#"itemPage"]objectForKey:#"page"];;
NSLog(#"%#",respArray1);
NSArray *respArray2= [[json objectForKey:#"response"]objectForKey:#"hot_program_by_category"];
NSLog(#"%#",respArray2);
for (NSDictionary *dic in [[respArray2 valueForKey:#"itemPage"]valueForKey:#"page"])
{
NSLog(#"%#",dic);
}
and don't forget to reload a tableview..i commented there just uncomment it

Use ASIHTTPRequest to startAsynchronous and update UITableView but failed with EXC_BAD_ACCESS

in viewDidLoad
{
[super viewDidLoad];
postjson = [[PostJson alloc] init];
[postjson startpost];
_table = [[UITableView alloc] init];
FOOTPRINT;
_table.delegate = self;
_table.dataSource =self;
[self.view addSubview:_table];
}
in startpost
-(NSMutableArray*)startpost:(NSString *)title category_id:(NSString *)category_id limits:(NSNumber *)limits blog_id:(NSString*)blog_id pull_direction:(NSString *)pull_dirction
{
__block NSMutableArray *dataToBeShown =[[NSMutableArray alloc] init];
__block NSMutableDictionary *resultsDictionary;
NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:title, #"title",category_id,#"category_id",limits,#"limits",blog_id,#"blog_id", pull_dirction,#"pull_direction",nil];
if ([NSJSONSerialization isValidJSONObject:userDictionary])
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error];
NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
NSURL *url = [NSURL URLWithString:[[PropertyPlist getValue:#"RootURL"] stringByAppendingString:#"/rest/blog/search"]];
ASIHTTPRequest *_request = [ASIHTTPRequest requestWithURL:url];
__weak ASIHTTPRequest* request = _request;
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request setRequestMethod:#"POST"];
[request setPostBody:tempJsonData];
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *response = [request responseString];
NSLog(#"Test:%#",response);
NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding];
FOOTPRINT;
resultsDictionary = [jsonData objectFromJSONData];
NSArray *dataArray = [resultsDictionary objectForKey:#"data"];
NSLog(#"即将进入FOR循环");
int i =0;
for ( NSDictionary *dict in dataArray){
NSMutableArray *tempArray =[[NSMutableArray alloc] init];
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"id"]];//取出ID
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"thumb"]];//取出缩略图地址
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"title"]];//取出title
[tempArray addObject:[[dataArray objectAtIndex:i] objectForKey:#"auto_id"]];//取出auto_id
[dataToBeShown addObject:tempArray];
tempArray=nil;
i++;
}
NSLog(#"跳出FOR循环");
}];
[request setFailedBlock:^{
NSError *error1 = [request error];
NSLog(#"ERROR IS %#",error1);
}];
[request startAsynchronous];
[ASIHTTPRequest setDefaultUserAgentString:kUserAgentString];
}
return dataToBeShown;
METHOD_END;
}
in cellForRowAtIndexPath
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *indentifier=#"indentifier";
RecommedTableViewCell *cell =(RecommedTableViewCell *)[tableView dequeueReusableCellWithIdentifier:indentifier];
if (cell == NULL)
{
cell=[[RecommedTableViewCell alloc]init]; }
NSInteger row=[indexPath row];
cell.titleLabel.text =[[dataToBeShown objectAtIndex:row] objectAtIndex:2];
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
return cell;
}
It will crash as soon as the app is started for EXC_BAD_ACCESS.When I commit out
cell.titleLabel.text =[[dataToBeShown objectAtIndex:row] objectAtIndex:2];
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
,not crash.So I found the dataToBeShown is null.How can I do it?
Please check the array before assigning
if(row
[cell.image setImageWithURL:[[dataToBeShown objectAtIndex:row] objectAtIndex:1] ];
}
or do the checking in numberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return dataToBeShown.count;
}
This will remove the EXC_BAD_ACCESS.

NSInvalidArgumentException reason: data parameter is nil in UITableView while trying to display the Flickr images

Hi in my application I want to display the Flickr album list in UITableView so i have searched for long time and i have found some solution. I have used the method which given in the solution its not working its giving error like
NSInvalidArgumentException', reason: 'data parameter is nil
The solution link click here
And since I'm trying this for first time I'm not able resolve this issue. This is MY API LINK for Flickr
I have used this code to display the Flickr image Album list in UItableview
{
NSMutableArray *photoURLs;
NSMutableArray *photoSetNames;
NSMutableArray *photoid1;
}
My Flickr API key
#define FlickrAPIKey #"a6a0c7d5efccffc285b0fe5ee1d938e3"
- (void)viewDidLoad
{
[super viewDidLoad];
photoURLs = [[NSMutableArray alloc] init];
photoSetNames = [[NSMutableArray alloc] init];
photoid1 = [[NSMutableArray alloc] init];
[self loadFlickrPhotos];
}
My TableView code
- (void)loadFlickrPhotos
{
NSString *urlString = [NSString stringWithFormat:#"http://api.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=%#&user_id=%#&per_page=10&format=json&nojsoncallback=1", FlickrAPIKey, #"124757153#N04"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *photoid = [photoset objectForKey:#"id"];
[photoid1 addObject:photoid];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [photoSetNames count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier =#"Cell";
flickrpoliticalCell *cell =(flickrpoliticalCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[flickrpoliticalCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.tit.text = [photoSetNames objectAtIndex:indexPath.row];
return cell;
}
try this
- (void)loadFlickrPhotos
{
//
NSString *urlString = [NSString stringWithFormat:#"https://www.flickr.com/services/rest/?method=flickr.photosets.getList&api_key=a6a0c7d5efccffc285b0fe5ee1d938e3&format=json&user_id=124757153#N04&per_page=10&nojsoncallback=1",nil];
NSLog(#"the url string==%#",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"the str==%#",jsonString);
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *photosets = [[results objectForKey:#"photosets"] objectForKey:#"photoset"];
for (NSDictionary *photoset in photosets) {
NSString *title = [[photoset objectForKey:#"title"] objectForKey:#"_content"];
NSLog(#"title==%#",title);
[photoSetNames addObject:(title.length > 0 ? title : #"Untitled")];
NSString *primary = [photoset objectForKey:#"primary"];
NSString *server = [photoset objectForKey:#"server"];
NSString *secret = [photoset objectForKey:#"secret"];
NSString *farm = [photoset objectForKey:#"farm"];
NSString *urlstr=[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg",farm,server,primary,secret];
NSLog(#"your photo id==%#",urlstr);
[photoids addObject:urlstr];
}
}

Getting response of weather application latitude,longitude values from server

I made the coding of getting weather application response.I could not get the exact latitude,longitude and population value.Instead of exact value i am getting response as a null.After that i cant get the other response.Also the response is-> " Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' "
Something i have done wrong in array index format.So anyone help me to get all values?
This is my coding
.M part
-(void)viewDidLoad
{
[super viewDidLoad];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"POST"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *dict1 =[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
//NSDictionary *dict1a =[dict1 objectForKey:#"JSON"];
NSDictionary *dict2 = [dict1 objectForKey:#"search_api"];
NSArray *array1 =[dict2 objectForKey:#"result"];
for(int i=0;i<[array1 count]; i++)
{
NSDictionary *dict3 =[array1 objectAtIndex:i];
NSArray *array2 =[dict3 objectForKey:#"areaName"];
NSDictionary *dict4 =[array2 objectAtIndex:i];
// NSArray *arr3 =[dict4 objectForKey:#"London"];
//manage.transformName= [NSString stringWithFormat:#"%#",[venueNem objectForKey:#"username"]];
NSString *str1= [NSString stringWithFormat:#"%#",[dict4 objectForKey:#"value"]];
NSLog(#"the response ==%#",str1);
NSArray *array3 =[dict3 objectForKey:#"country"];
NSDictionary *dict5 =[array3 objectAtIndex:i];
NSString *str2 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"value"]];
NSLog(#"the response ==%#",str2);
NSString *str3 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str3);
NSString *str4 =[NSString stringWithFormat:#"%#",[dict5 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str4);
NSString *str5 = [NSString stringWithFormat:#"%#",[dict5 objectForKey:#"population"]];
NSLog(#"the response ==%#",str5);
NSArray *arr4 =[dict3 objectForKey:#"region"];
NSDictionary *dict6 =[arr4 objectAtIndex:i];
NSString *str6 = [NSString stringWithFormat:#"%#",[dict6 objectForKey:#"value"]];
NSLog(#"the response ==%#",str6);
NSArray *arr5 =[dict3 objectForKey:#"weatherUrl"];
NSDictionary *dict7 =[arr5 objectAtIndex:i];
NSString *str7 =[NSString stringWithFormat:#"%#",[dict7 objectForKey:#"value"]];
NSLog(#"the response ==%#",str7);
}
for(int j=0;j<[array1 count];j++)
{
NSDictionary *dict8 =[array1 objectAtIndex:j];
NSArray *arr6 =[dict8 objectForKey:#"areaname"];
NSDictionary *dict9 =[arr6 objectAtIndex:j];
NSString *str8 =[NSString stringWithFormat:#"%#",[dict9 objectForKey:#"value"]];
NSLog(#"the response ==%#",str8);
NSArray *arr7 =[dict8 objectForKey:#"country"];
NSDictionary *dict10 =[arr7 objectAtIndex:j];
NSString *str9 =[NSString stringWithFormat:#"%#",[dict10 objectForKey:#"value"]];
NSLog(#"the response ==%#",str9);
NSString *str10 =[NSString stringWithFormat:#"%f",[dict10 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str10);
NSString *str11 =[NSString stringWithFormat:#"%f",[dict10 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str11);
NSString *str12 =[NSString stringWithFormat:#"%d",[dict10 objectForKey:#"population"]];
NSLog(#"the response ==%#",str12);
NSArray *arr8 =[dict8 objectForKey:#"region"];
NSDictionary *dict11 =[arr8 objectAtIndex:j];
NSString *str13 =[NSString stringWithFormat:#"%#",[dict11 objectForKey:#"value"]];
NSLog(#"the response ==%#",str13);
NSArray *arr9 =[dict8 objectForKey:#"weatherurl"];
NSDictionary *dict12 =[arr9 objectAtIndex:j];
NSString *str14 =[NSString stringWithFormat:#"%#",[dict12 objectForKey:#"value"]];
NSLog(#"the response ==%#",str14);
}
NSDictionary *dict13 =[array1 objectAtIndex:2];
NSArray *arr10 =[dict13 objectForKey:#"areaname"];
NSDictionary *dict14 =[arr10 objectAtIndex:2];
NSString *str15 =[NSString stringWithFormat:#"%#",[dict14 objectForKey:#"value"]];
NSLog(#"the response ==%#",str15);
NSArray *arr11 =[dict13 objectForKey:#"country"];
NSDictionary *dict15 =[arr11 objectAtIndex:2];
NSString *str16 =[NSString stringWithFormat:#"%#",[dict15 objectForKey:#"value"]];
NSLog(#"the response ==%#",str16);
NSString *str17 =[NSString stringWithFormat:#"%f",[dict15 objectForKey:#"latitude"]];
NSLog(#"the response ==%#",str17);
NSString *str18 =[NSString stringWithFormat:#"%f",[dict15 objectForKey:#"longitude"]];
NSLog(#"the response ==%#",str18);
NSString *str19 =[NSString stringWithFormat:#"%d",[dict15 objectForKey:#"population"]];
NSLog(#"the response ==%#",str19);
NSArray *arr12 =[dict13 objectForKey:#"region"];
NSDictionary *dict16 =[arr12 objectAtIndex:2];
NSString *str20 =[NSString stringWithFormat:#"%#",[dict16 objectForKey:#"value"]];
NSLog(#"the response ==%#",str20);
NSArray *arr13 =[dict13 objectForKey:#"weatherurl"];
NSDictionary *dict17 =[arr13 objectAtIndex:2];
NSString *str21 =[NSString stringWithFormat:#"%#",[dict17 objectForKey:#"value"]];
NSLog(#"the response ==%#",str21); }
Look at you first FOR loop. I am not saying the error is in only there.
EDIT
for(int i=0;i<[array1 count]; i++)
{
NSDictionary *dict3 =[array1 objectAtIndex:i];
NSArray *key = [dict3 allKeys];
for (int j = 0; j < key.count ; j++) {
if ([[key objectAtIndex:j] isEqualToString:#"areaName"]) {
NSArray *array2 =[dict3 objectForKey:#"areaName"];
//Area name
NSString *area = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"country"]){
NSArray *array2 =[dict3 objectForKey:#"country"];
//Country
NSString *country = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"latitude"]){
//Latitude
NSString *latitude = [dict3 objectForKey:#"latitude"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"longitude"]){
//longitude
NSString *longitude = [dict3 objectForKey:#"longitude"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"population"]){
//population
NSString *population = [dict3 objectForKey:#"population"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"region"]){
NSArray *array2 =[dict3 objectForKey:#"region"];
//region
NSString *region = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
else if ([[key objectAtIndex:j] isEqualToString:#"weatherUrl"]){
NSArray *array2 =[dict3 objectForKey:#"weatherUrl"];
//weatherUrl
NSString *weatherUrl = [[array2 objectAtIndex:0] objectForKey:#"value"];
}
}
}
arra=[[NSMutableArray alloc]init];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonArray objectForKey:#"search_api"]objectForKey:#"result"];
for (int i=0; i<[array count]; i++) {
NSLog(#"the areaName==%#",[[[[array objectAtIndex:i]objectForKey:#"areaName"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the country==%#",[[[[array objectAtIndex:i]objectForKey:#"country"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the latitude==%#",[[array objectAtIndex:i]objectForKey:#"latitude"]);
NSLog(#"the long==%#",[[array objectAtIndex:i]objectForKey:#"longitude"]);
NSLog(#"the pop==%#",[[array objectAtIndex:i]objectForKey:#"population"]);
NSLog(#"the region==%#",[[[[array objectAtIndex:i]objectForKey:#"region"]objectAtIndex:0]objectForKey:#"value"]);
NSLog(#"the url==%#",[[[[array objectAtIndex:i]objectForKey:#"weatherUrl"]objectAtIndex:0]objectForKey:#"value"]);
NSString *areaName=[[[[array objectAtIndex:i]objectForKey:#"areaName"]objectAtIndex:0]objectForKey:#"value"];
[arra addObject:areaName];
}

Resources