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
Related
how to display the key on tableview at the same time?
Here I can display the value.
I want to show the key on cell.textLabel setText:#"A"
Please..
.
.
.
Here is my code
ThankYou
Thankyou very much.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://reserve.cdn-apple.com/AU/en_AU/reserve/iPhone/availability.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
_listarr = [[NSMutableArray alloc]init];
id list = [dic objectForKey:self.strStore];
if ([list isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = (NSDictionary *)list;
NSArray *keys = [list allKeys];
for (NSString *key in keys) {
NSString *teamname = (NSString *)[dictionary objectForKey:key];
NSLog(#"",key);
[_listarr addObject:[NSString stringWithFormat:#"%#", teamname]];
}
} else {
// Do some error handling
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//必须返回与数据容器一样的数量,否则会报数据越界错
return [_listarr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"thisCell";
UITableViewCell *cell;
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell.textLabel setText:#"A"];
[cell.detailTextLabel setText:[_listarr objectAtIndex:indexPath.row]];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
#end
Hi this code will give you what you required I think..
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSArray *array = [dic allKeys];
NSArray *temparray = [dic objectsForKeys:array notFoundMarker:[NSNull null]];
Use NSDictionary's allKeysForObject: to look up keys that match an object. Objects are compared with isEqual: and should match for simple NSStrings.
If the array is too large, this may be slow, in which case you might create another array with the key values that you can index quickly.
Good afternoon,
I'm trying to use a NSMutableArray in my TableViewController from a JSON output and I'm a little bit lost because currently I can store my JSON data in a NSMutableArray, and I have checked with a NSLog that the content is OK, but now I have to show that data in my TableViewController and that's when I'm lost.
I'm using an another example of TableViewController using NSArray but now I have to modify it for a NSMutableArray. If you can help me with some code or show me some examples or tutorials I will be much appreciated.
I know in my code maybe I have something wrong because I'm using an old example using only NSArray but I'm showing you because that's what I don't know how to do, I need to work with NSMutableArray and that's why I'm asking for your help.
How can I show a NSMutableArray in my TableViewController?
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
}
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
//NSError * error;
//NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// I advice that you make your carModels mutable array and initialise it here,before start working with json
//self.carModels = [[NSMutableArray alloc] init];
NSMutableArray *carModels=[[NSMutableArray alloc]init];
NSMutableArray *carMakes=[[NSMutableArray alloc]init];
NSMutableArray *carImages=[[NSMutableArray alloc]init];
#try
{
NSError *error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
if (error)
{
NSLog(#"%#",[error localizedDescription]);
}
else
{
for(int i=0;i<json.count;i++)
{
NSDictionary * jsonObject = [json objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[carImages addObject:imagen];
NSDictionary * jsonObject2 = [json objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[carMakes addObject:user];
NSDictionary * jsonObject3 = [json objectAtIndex:i];
NSString* images = [jsonObject3 objectForKey:#"date"];
[carModels addObject:images];
}
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
}
#finally
{
NSLog(#"finally");
// That's showing the data "1, 2, 3".
NSLog(#"models: %#", carModels);
NSLog(#"makes: %#", carMakes);
NSLog(#"images: %#", carImages);
}
}
);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.carModels count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [_carMakes objectAtIndex: [indexPath row]];
cell.modelLabel.text = [self.carModels objectAtIndex:[indexPath row]];
UIImage *carPhoto = [UIImage imageNamed: [self.carImages objectAtIndex: [indexPath row]]];
cell.carImage.image = carPhoto;
return cell;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ShowCarDetails"])
{
CarDetailViewController *detailViewController =
[segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView
indexPathForSelectedRow];
detailViewController.carDetailModel = [[NSArray alloc]
initWithObjects: [self.carMakes
objectAtIndex:[myIndexPath row]],
[self.carModels objectAtIndex:[myIndexPath row]],
[self.carImages objectAtIndex:[myIndexPath row]],
nil];
}
}
Thanks.
Declare NSMutableArray *jsonArray ; as global
-(void)fetchJson {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
//NSError * error;
//NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// I advice that you make your carModels mutable array and initialise it here,before start working with json
//self.carModels = [[NSMutableArray alloc] init];
#try
{
NSError *error;
[jsonArray removeAllObjects];
jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
}
#finally
{
[self.tableView reloadData]
}
}
);
}
To Display The TableView Like This
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [jsonArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [[jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"];
cell.modelLabel.text = [[jsonArray objectAtIndex:indexPath.row] valueForKey:#"user"];
UIImage *carPhoto = [[jsonArray objectAtIndex:indexPath.row] valueForKey:#"date"];
cell.carImage.image = carPhoto;
return cell;
}
Add
[self.tableView reloadData]
after you have fetched and parsed the JSON.
Whenever you change table datas from different array just add [self.tableView reloadData] in you method.
It will remove old data & shows new data into your tableview.
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"];
}
}
My question:
in json can not properly address the image. Each line corresponds to the incorrect image is coming. Comes in 3 different sizes. How to parse them TableView 's imageviewer' How do I dispose of. Thank you.
ScreenShot:
My code:
#import "TableViewController.h"
#interface TableViewController (){
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *labelArray;
NSMutableArray *imageArray;
}
#end
#implementation TableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *removeAllData = [NSMutableArray arrayWithObjects:imageArray,labelArray,nil];
[removeAllData removeAllObjects];
[self.tableView setDelegate:self];
[self.tableView setDataSource:self];
labelArray = [[NSMutableArray alloc]init];
imageArray = [[NSMutableArray alloc]init];
NSString *strURL = #"https://itunes.apple.com/tr/rss/newapplications/limit=25/json";
NSURL *url = [NSURL URLWithString:strURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData = [[NSMutableData alloc]init];
}
}
-(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");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:nil];
NSDictionary *allFeedDictionary = [allDataDictionary objectForKey:#"feed"];
NSArray *arrayOfEntry = [allFeedDictionary objectForKey:#"entry"];
for (NSDictionary *diction in arrayOfEntry) {
NSDictionary *title = [diction objectForKey:#"title"];
NSDictionary *imImage = [diction objectForKey:#"im:image"];
for (NSDictionary *imageDict in imImage) {
NSDictionary *imageLabel = [imageDict objectForKey:#"label"];
[imageArray addObject:imageLabel];
}
NSString *label = [title objectForKey:#"label"];
[labelArray addObject:label];
}
[self.tableView reloadData];
NSLog(#"%#",[imageArray objectAtIndex:0]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return labelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
//NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [imageArray objectAtIndex:indexPath.row]]];
NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[imageArray objectAtIndex:indexPath.row]]];
UIImage *image = [[UIImage alloc] initWithData:imageData];
cell.textLabel.text = [labelArray objectAtIndex:indexPath.row];
cell.imageView.image = image;
return cell;
}
for (NSDictionary *imageDict in imImage) {
NSDictionary *imageLabel = [imageDict objectForKey:#"label"];
[imageArray addObject:imageLabel];
break;
}
OR
[imageArray addObject: imImage[0][#"label"]];
Just replace this in your code. You need to break the loop as your required size image always lies at 0th index.
i have an array that contains 5 items when i debugging but when i try to bind them to a tableview the tableview is empty without error.
It works if a do an array manually and initwithobjects but i already have an array.
After this my array have 5 objects
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
The problem is the part where i try to init the array.
If i do this my array is null after.
array = [[NSMutableArray alloc] init];
and if i do this my array still have 5 object but not loaded into table
array = [array init];
Thanks for your help
All Code
NSArray *array;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *request = [NSString stringWithFormat:
#"http://192.168.99.99/IBookService.svc/GetBooksNames"];
NSURL *URL = [NSURL URLWithString:
[request stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:URL options:NSDataReadingUncached error:&error];
if(!error)
{
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
array = [[NSMutableArray alloc] init];
}
_tblCustomers.dataSource = self;
_tblCustomers.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identity = #"custTbl";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity];
if (cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identity];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
You add object to the array and after that you allocate it (clear it). Do it other way around:
if(!error)
{
array = [[NSMutableArray alloc] init];
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
Currently array is deallocated when you leave viewDidLoad method. You should make array a member of class to avoid this. For example you can add following
{
NSArray *array;
}
after line
#implementation Your_class_name_here
And delete your current line
NSArray *array;