model class data Retriving - ios

I have implemented a UITableview in ViewController1 and retrieving the data from JSON. I Want to display the cell with the Image,Tittle and Sub tittle.I am using a TableClass as model class for that
dispatch_async(dispatch_get_main_queue(), ^{
NSURLSession*session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"https://itunes.apple.com/search?term=music"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);
NSArray*entryarr=[json objectForKey:#"results"];
TableClass*tc=[[TableClass alloc]init];
for (NSDictionary*appDict in entryarr) {
NSString*str=[appDict objectForKey:#"artistName"];
[tc setTittle:str];
NSLog(#"artist Name=%#",tc.tittle);
//setting Subtittle
NSString*sub=[appDict objectForKey:#"country"];
[tc setSubtittle:sub];
NSLog(#"artist Name=%#",tc.subtittle);
NSString*imageStr=[appDict objectForKey:#"artworkUrl60"];
[tc setImage:imageStr];
NSURL*imageURL=[NSURL URLWithString:imageStr];
NSData*imageData=[[NSData alloc]initWithContentsOfURL:imageURL];
[self.imageArray addObject:imageData];
[_tableArray addObject:tc];
NSLog(#"%# name of tittle",[_tableArray objectAtIndex:0]);
}
NSLog(#"%lu %lu %lu",(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count);
[self.tableView reloadData];
}];
[dataTask resume];
});
}
But Now i display the data By
cell.textLabel.text=[[self.tableArray objectAtIndex:indexPath.row]valueForKey:#"_tittle"];
cell.detailTextLabel.text=[[self.tableArray objectAtIndex:indexPath.row]valueForKey:#"_subtittle"];
cell.imageView.image=[UIImage imageWithData:[[self.tableArray objectAtIndex:indexPath.row]valueForKey:#"_image"]];
But I feel that method is not optimise, So I want to display Data through Model class itself How can i do it...?

TableClass.h
#import <Foundation/Foundation.h>
#interface TableClass : NSObject
#property(nonatomic,strong) NSString *title;
#property(nonatomic,strong) NSString *subtittle;
#property(nonatomic,strong) NSString *imageURL;
#property(nonatomic,strong) NSData *imageData;
#end
in your ViewController.m
-(void)getData
{
NSURLSession*session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"https://itunes.apple.com/search?term=music"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);
NSArray*entryarr=[json objectForKey:#"results"];
self.tableArray=[[NSMutableArray alloc]init];
for (NSDictionary*appDict in entryarr)
{
TableClass *classModel=[[TableClass alloc]init];
classModel.title=[appDict objectForKey:#"artistName"];
classModel.subtittle=[appDict objectForKey:#"country"];
classModel.imageURL=[appDict objectForKey:#"artworkUrl60"];
classModel.imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:classModel.imageURL]];
[self.tableArray addObject:classModel];
}
NSLog(#"%lu %lu %lu",(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count);
dispatch_async(dispatch_get_main_queue(), ^{
//update UI in main thread.
[self.myTableView reloadData];
});
}];
[dataTask resume];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.tableArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier= #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
TableClass *tableclassModel=[self.tableArray objectAtIndex:indexPath.row];
cell.textLabel.text=tableclassModel.title;
cell.detailTextLabel.text=tableclassModel.subtittle;
[cell.imageView setImage:[UIImage imageWithData:tableclassModel.imageData]];
return cell;
}
In this example you don't need an extra array to store images.
Let me know if you have any query.

Related

Getting a json file from a website into UITableview with Objective C

I'm attempting to get a json file from a website into UITableview with Objective C.
As I'm not an advanced coder please excuse my crude coding tecniques.
I have a .json file uploaded to my webspace. The File is formatted as so:
"JSONDATA":[
{
"name": "ABC",
"details": "DEF"
},
{
"name": "UVW",
"details": "XYZ"
}
]
my .h looks like:
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
IBOutlet UITableView *myTableView;
}
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#end
the .m code
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrName;
NSMutableArray *arrDetails;
NSString *responseString;
}
#end
#implementation ViewController
#synthesize myTableView;
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"ViewDidLoad");
[self fetchData];
[myTableView reloadData];
}
-(void)fetchData
{
NSLog(#"GetJsonResponse Fired");
NSURL *URL = [NSURL URLWithString:#"http://myWebsite.com/json/myJsonFile.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSLog(#"URLRequest = %#",request);
/////////////////////////////////////////////////////////////////// Nothing Below Here Fires/////////////////////////////////////////////////
// [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:ourBlock];
[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
{
// Block Body
NSLog(#"response = %#",response);
NSLog(#"block Body");
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"GetJsonDict%#",jsonDict);
NSArray *arr = jsonDict[#"JSONFILE"];
NSLog(#"jasoDict = %#",arr);
self->arrName = [[NSMutableArray alloc]init];
self->arrDetails = [[NSMutableArray alloc]init];
//arrValue = [[NSMutableArray alloc]init];
for(int i=0;i<[arr count];i++)
{
NSString *strName = [arr[i]objectForKey:#"NAME"];
NSString *strCode = [arr[i]objectForKey:#"CODE"];
// NSString *strValue = [arr[i]objectForKey:#"VALUE"];
NSLog(#"The strName is - %#",strName);
NSLog(#"The strCode is - %#", strCode);
// NSLog(#"The strValue is - %#", strValue);
[self->arrName addObject:strName];
[self->arrDetails addObject:strCode];
// [arrValue addObject:strValue];
NSLog(#"The arrName is - %#",self->arrName);
NSLog(#"The arrDetails is - %#", self->arrDetails);
// NSLog(#"The arrValue is - %#", arrValue);
}
}];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrName.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"Cell";
// UITableViewCell *cell = [UITableView dequeueReusableCellWithIdentifier:strCell];
UITableViewCell *cell = [myTableView dequeueReusableCellWithIdentifier:strCell forIndexPath:indexPath];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCell];
}
cell.textLabel.text = arrName[indexPath.row];
cell.detailTextLabel.text = arrDetails[indexPath.row];
return cell;
}
#end
I can't seem to put all the pieces together and get any data through to parse.
The NSLog is telling me:
2020-03-09 14:13:42.605558-0500 jsonFromWeb[27389:1317924] ViewDidLoad
2020-03-09 14:13:42.605802-0500 jsonFromWeb[27389:1317924] GetJsonResponse Fired
2020-03-09 14:13:42.606118-0500 jsonFromWeb[27389:1317924] URLRequest = <NSURLRequest: 0x6000001f8cc0> { URL: http://mywebsite.com/json/myJsonFile.json }
Where is this thing derailing? I can't get any data out of the URLResponse.
Thanks so much.
You have to resume the data task and you have to reload the table view inside the completion block on the main thread
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
...
}
dispatch_async(dispatch_get_main_queue(), ^{
[myTableView reloadData];
});
}] resume];

how do get values when i click on particular country dynamically like this is showing of india

How to get value from json?
this is first api
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/countries/?format=json"];
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodedUrlAsString = [urlAsString stringByAddingPercentEncodingWithAllowedCharacters:set];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithURL:[NSURL URLWithString:encodedUrlAsString]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"RESPONSE: %#",response);
NSLog(#"DATA: %#",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
} else {
// Success Parsing JSON
// Log NSDictionary response:
arr = [jsonResponse valueForKey:#"countries"];
NSLog(#"%#",arr);
[self.tableView reloadData];
}
} else {
//Web server is returning an error
}
} else {
// Fail
NSLog(#"error : %#", error.description);
}
}] resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor yellowColor];
cell.textLabel.text = [arr objectAtIndex:indexPath.row ];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *str = [arr objectAtIndex:indexPath.row] ;
ViewController1 *vc=[self.storyboard instantiateViewControllerWithIdentifier:#"ViewController1"];
vc.str1 = [arr objectAtIndex:indexPath.row];
[self.navigationController pushViewController:vc animated:YES];
}
this is second one
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/wp-rank/1952-03-11/male/India/on/2001-05-11/?format=json"];
NSString *encodedString = [urlAsString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithURL:[NSURL URLWithString:encodedString]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"RESPONSE: %#",response);
NSLog(#"DATA: %#",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
} else {
// Success Parsing JSON
// Log NSDictionary response:
// _str2 = [jsonResponse valueForKey:#"dob"];
/// NSLog(#"%#",_str2);
NSLog(#"%#",jsonResponse);
}
}
}
}
when i click particular country i should get data from that country
you need to use that str1 property that you are setting in didSelect method to make your URL, so replace the India with str1's value.
NSString *urlAsString = [NSString stringWithFormat:#"http://api.population.io/1.0/wp-rank/1952-03-11/male/%#/on/2001-05-11/?format=json", self.str1];
Note: You need to give proper name to your property, so better if you changed str1 to selectedCountry or something else.

Tableview data pass through Model Class

I have implemented a UITableview in VC1, and I want to display some JSON data in the cell. I have implemented a Model class to pass the data to the table view.
dispatch_async(dispatch_get_main_queue(), ^{
NSURLSession*session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"https://itunes.apple.com/search?term=music"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);
NSArray *entryarr = [json objectForKey:#"results"];
TableClass *tc = [[TableClass alloc] init];
for (NSDictionary *appDict in entryarr) {
//setting title
NSString *str = [appDict objectForKey:#"artistName"];
[tc setTittle:str];
NSLog(#"artist Name=%#",tc.tittle);
//setting Subtitle
NSString *sub = [appDict objectForKey:#"country"];
[tc setSubtittle:sub];
NSLog(#"artist Name=%#",tc.subtittle);
//image
NSString *imageStr = [appDict objectForKey:#"artworkUrl60"];
NSURL *imageURL = [NSURL URLWithString:imageStr];
[tc setImage:imageStr];
NSData *imageData =[[NSData alloc] initWithContentsOfURL:imageURL];
//[self.imageArray addObject:imageData];
[_tableArray addObject:tc];
NSLog(#"%# name of tittle",[_tableArray objectAtIndex:0]);
}
NSLog(#"%lu %lu %lu",(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count);
[self.tableView reloadData];
}];
[dataTask resume];
});
But, while accessing it to the cell I am getting the last element in the array.
TableClass *tableclassModel = [self.tableArray objectAtIndex:indexPath.row];
cell.textLabel.text = tableclassModel.tittle;
cell.detailTextLabel.text = tableclassModel.subtittle;
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:tableclassModel.image]]];
Why is it so...? How can I do it?
You are changing the value of same tc object again and again. Since you have declared tc object outside for loop, there will be only one tc. You are adding it to _tableArray after making the required changes in the first iteration of the loop. In the second iteration, you are changing the value of same tc object used in first iteration and adding it to _tableArray again. This will update the first object also with the new values. This goes on and finally your _tableArray will contain n number of tc objects with the same values (i.e last updated value)
Give the declaration inside the for loop
dispatch_async(dispatch_get_main_queue(), ^{
NSURLSession*session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:#"https://itunes.apple.com/search?term=music"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);
NSArray*entryarr=[json objectForKey:#"results"];
for (NSDictionary*appDict in entryarr) {
TableClass*tc=[[TableClass alloc]init];
//setting tittl
NSString*str=[appDict objectForKey:#"artistName"];
[tc setTittle:str];
NSLog(#"artist Name=%#",tc.tittle);
//setting Subtittle
NSString*sub=[appDict objectForKey:#"country"];
[tc setSubtittle:sub];
NSLog(#"artist Name=%#",tc.subtittle);
//image
NSString*imageStr=[appDict objectForKey:#"artworkUrl60"];
NSURL*imageURL=[NSURL URLWithString:imageStr];
[tc setImage:imageStr];
NSData*imageData=[[NSData alloc]initWithContentsOfURL:imageURL];
//[self.imageArray addObject:imageData];
[_tableArray addObject:tc];
NSLog(#"%# name of tittle",[_tableArray objectAtIndex:0]);
}
NSLog(#"%lu %lu %lu",(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count,(unsigned long)self.tableArray.count);
[self.tableView reloadData];
}];
[dataTask resume];
});

Data dosen't load on some Tableview cell from JSON parse

I making here simple application on XCODE 7.1. I just display 2 label and 1 image in tableview cell.I am parsing data from this URL. I am simply load data in TableviewHere i put the code of ViewController.m file
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.alpha = 1.0;
[self.view addSubview:activityIndicator];
activityIndicator.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
[activityIndicator startAnimating];//to start animating
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
[activityIndicator stopAnimating];
_responsedic = (NSDictionary*) responseObject;
_Worldpopulation = [_responsedic valueForKey:#"worldpopulation"];
_imageURL = [_Worldpopulation valueForKey:#"flag"];
_country = [_Worldpopulation valueForKey:#"country"];
_population = [_Worldpopulation valueForKey:#"population"];
NSLog(#"Data:%#",_imageURL);
NSLog(#"Population",_population);
NSLog(#"Country",_country);
// NSLog(#"%#",_MovieList);
//NSLog(#"Array: %#",_imageURL);
//NSLog(#"%#",responseObject);
}
}];
[dataTask resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *Identifier = #"mycell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Identifier];
// Set and load the images
[cell.imageView sd_setImageWithURL:[_imageURL objectAtIndex:indexPath.row] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
// Get rid of the activity indicator when the image has been loaded
}];
cell.textLabel.text = [_country objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [_population objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//NSString *rowValue = self.friends[indexPath.row+1];
NSString *message = [[NSString alloc] initWithFormat:#"You selected %#",[_country objectAtIndex:indexPath.row]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"YOU SELECT"
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
I am using AFNetworking 3.0 and SDWebImage for image loading.Data parse successfully and and displayed in tableview.I attached screenshot below
Problem is what the all data are not displayed in the tableview cell i also put the Alert dialog on each cell of tableview data successfully loaded but not displayed in cell. I search everywhere i can't find solution for this i am using 3G connection so net speed is not an issue Please someone help.
Try to reload table view with updated data in completion block.
NSURL *URL = [NSURL URLWithString:#"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
[activityIndicator stopAnimating];
_responsedic = (NSDictionary*) responseObject;
_Worldpopulation = [_responsedic valueForKey:#"worldpopulation"];
_imageURL = [_Worldpopulation valueForKey:#"flag"];
_country = [_Worldpopulation valueForKey:#"country"];
_population = [_Worldpopulation valueForKey:#"population"];
NSLog(#"Data:%#",_imageURL);
NSLog(#"Population",_population);
NSLog(#"Country",_country);
// NSLog(#"%#",_MovieList);
//NSLog(#"Array: %#",_imageURL);
//NSLog(#"%#",responseObject);
//Added Code -> Reloading data on Main queue for update
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableview reloadData];
});
}
}];
[dataTask resume];
Hope, it'll help you.
Thanks.
1) Parse Data and after getting data relaod table
-(void)ParseData
{
NSURLSession * session = [NSURLSession sharedSession];
NSURL * url = [NSURL URLWithString: #"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
//Create URLReques
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// Set Method POST/GET
[request setHTTPMethod:#"GET"];
// Asynchronously Api is hit here
NSURLSessionDataTask* dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) //If error nil
{
//Serialization data
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"json %#",json);
array=[json valueForKey:#"worldpopulation"];
dispatch_async(dispatch_get_main_queue(), ^(void) {
if(array.count!=0)
{
//Reload table View
[_tblView reloadData];
}
});
}
else
{
//failure;
}
}];
[dataTask resume] ; // Executed task
}
2) Table View DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(array.count!=0)
{
return [array count];
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
//= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.backgroundColor =[UIColor whiteColor];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UILabel *lblCountry=(UILabel*)[cell viewWithTag:2];
lblCountry.text= [[array objectAtIndex:indexPath.row]valueForKey:#"country"];
UILabel *lblPopulation=(UILabel*)[cell viewWithTag:3];
lblPopulation.text= [[array objectAtIndex:indexPath.row]valueForKey:#"population"];
UIImageView *img = (UIImageView *)[cell viewWithTag:1];
[img setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row]valueForKey:#"flag"]]];
return cell;
}

Parsing data from googleapi

I'm trying to build an app that uses data from this url: http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss
So far, I'm downloading it with this:
- (void) downloadData {
NSString *url = #"http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss";
// Create NSUrlSession
NSURLSession *session = [NSURLSession sharedSession];
// Create data download taks
[[session dataTaskWithURL:[NSURL URLWithString:url]
completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSError *jsonError;
self.issueData = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonError];
// Log the data for debugging
NSLog(#"DownloadedData:%#",self.issueData);
// Use dispatch_async to update the table on the main thread
// Remember that NSURLSession is downloading in the background
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}] resume];
}
and trying to insert it into my table view cells with this:
- (CustomTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"customTableViewCell" forIndexPath:indexPath];
NSLog(#"Working on cell:%ld",(long)indexPath.row);
NSDictionary *thread = [self.issueData objectAtIndex:indexPath.row];
cell.title.text = [thread objectForKey:#"description"];
cell.date.text = [thread objectForKey:#"publishedDate"];
cell.content.text = [thread objectForKey:#"contentSnippet"];
return cell;
Anyone know what I'm doing wrong?
Your top level object for json is not array so
NSDictionary *thread = [self.issueData objectAtIndex:indexPath.row]; this will not work. You top level object is dictionary so parsing will be as
(CustomTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"customTableViewCell" forIndexPath:indexPath];
NSLog(#"Working on cell:%ld",(long)indexPath.row);
NSDictionary *thread = [self.issueData objectForKey:#"responseData"];
NSDictionary *feed = [thread objectForKey:#"feed"];
cell.title.text = [feed objectForKey:#"description"];
NSArray *entries = [feed objectForKey:#"entries"];
NSDictionary *posts = entries[indexPath.row];
cell.date.text = [posts objectForKey:#"publishedDate"];
cell.content.text = [posts objectForKey:#"contentSnippet"];
return cell;
}
I guess right way for parsing it as follow's
- (void) downloadData {
NSString *url = #"http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=8&q=http%3A%2F%2Fnews.google.com%2Fnews%3Foutput%3Drss";
// Create NSUrlSession
NSURLSession *session = [NSURLSession sharedSession];
// Create data download taks
[[session dataTaskWithURL:[NSURL URLWithString:url]
completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSError *jsonError;
NSDictionary * dict;
dict= [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonError];
dispatch_async(dispatch_get_main_queue(), ^{
if ([dict valueForKey:#"responseData"]) {
if([[dict valueForKey:#"responseData"] isKindOfClass:[NSDictionary class]]){
if ([(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"]) {
if ([[(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"]isKindOfClass:[NSDictionary class]]) {
NSDictionary * feedDict = [(NSDictionary *)[dict valueForKey:#"responseData"] valueForKey:#"feed"];
if ([feedDict valueForKey:#"description"]){
NSLog(#"%#",[feedDict valueForKey:#"description"]);
}
if ([[feedDict valueForKey:#"entries"] isKindOfClass:[NSArray class]]){
for (NSDictionary * dic in (NSArray *)[feedDict valueForKey:#"entries"]) {
NSLog(#"published = %#",[dic valueForKey:#"publishedDate"]);
}
}
if ([[feedDict valueForKey:#"entries"] isKindOfClass:[NSArray class]] ){
for (NSDictionary * dic in (NSArray *)[feedDict valueForKey:#"entries"]) {
NSLog(#"contentSnippet = %#",[dic valueForKey:#"contentSnippet"]);
}
}
}
}
}
}
});
}] resume];}
I just logged the required keys to console you can add them to arrays and use them anywhere you want.

Resources