This is my first iOS7 iPhone Developer in XCode5 with JSON Data and UITableView step-by-step to show, how to display json data on UITableView
[sorry for my poor english]
[sorry for my poor english]
First my JSON Data is something like that...
Example
http://example.com/feed/json or http://example.com/?feed=json to anywhere you get a JSON form.
As you confirm, Xcode automatically creates the “JSONView” project based on the options you’ve provided. The resulting screen looks like this:
Goto MainStoryBoard from project solution tree on you left side and drag UITableView object, paste it on ViewController.
Press and hold the Control key on your keyboard, select the Table View and drag to the “File’s Owner”. Release both buttons and a popup shows both “dataSource” and “delegate”.
Insert one prototype cell on your UITableView
Next, select “ViewController.h” Append “<UITableViewDelegate, UITableViewDataSource>” after “UIViewController” and define an instance variable for holding the table data.
Chang this code below:
to
Next, select “ViewController.m” and define an instance variable for holding the table data.
In the “viewDidLoad” method, add the following code to initialize the JSON data array.
Add two datasource methods: “tableView:numberOfRowsInSection” and “tableView:cellForRowAtIndexPath”.
The first method is used to inform the table view how many rows are in the section. So let’s add the below code.
Run your project and see the NSlog Console it's will show.
The JSON data will import to UITableView and you first iOS7 will complete!
From my iOS Dev in Thailand community : Daydev.com [All Tutorial in Thai]
Source Code available: http://www.daydev.com/source-code-web-service-ios7-uitableview
[I used Wordpress CMS and install plug-in name "Feed JSON" to convert RSS Feed from my blog to a new type of feed you can subscribe to.
{
id: 844,
title: "Post From Wordpress Title",
permalink: "http://www.youweb.com/lillian-powers-vine/",
content: "Some Content from Post on Wordpress",
date: "2013-08-28 16:01:37",
author: "Banyapon Poolsawasd",
thumbnail: "http://www.youweb.com/wp-content/uploads/2013/08/image.png",
categories: [
"Comedy",
"Feature",
"Lifestyles",
"Techonlogy"
],
tags: [
"Lillian Powers",
"Lillian Powers Vine",
"Vine"
]
}
]
Example
http://example.com/feed/json or http://example.com/?feed=json to anywhere you get a JSON form.
Start!
First open Xcode5 and create New iPhone developer's Project in Single View Application and choose you project nameGoto MainStoryBoard from project solution tree on you left side and drag UITableView object, paste it on ViewController.
Press and hold the Control key on your keyboard, select the Table View and drag to the “File’s Owner”. Release both buttons and a popup shows both “dataSource” and “delegate”.
Insert one prototype cell on your UITableView
Next, select “ViewController.h” Append “<UITableViewDelegate, UITableViewDataSource>” after “UIViewController” and define an instance variable for holding the table data.
Chang this code below:
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
to
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource> { IBOutlet UITableView *tableData; } @end
Next, select “ViewController.m” and define an instance variable for holding the table data.
@interface ViewController () { NSMutableArray *myObject; // A dictionary object NSDictionary *dictionary; // Define keys NSString *title; NSString *thumbnail; NSString *author; } @end
In the “viewDidLoad” method, add the following code to initialize the JSON data array.
- (void)viewDidLoad { [super viewDidLoad]; title = @"title"; thumbnail = @"thumbnail"; author = @"author"; myObject = [[NSMutableArray alloc] init]; NSData *jsonSource = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://gooruism.com/feed/json"]]; id jsonObjects = [NSJSONSerialization JSONObjectWithData: jsonSource options:NSJSONReadingMutableContainers error:nil]; for (NSDictionary *dataDict in jsonObjects) { NSString *title_data = [dataDict objectForKey:@"title"]; NSString *thumbnail_data = [dataDict objectForKey:@"thumbnail"]; NSString *author_data = [dataDict objectForKey:@"author"]; NSLog(@"TITLE: %@",title_data); NSLog(@"THUMBNAIL: %@",thumbnail_data); NSLog(@"AUTHOR: %@",author_data); dictionary = [NSDictionary dictionaryWithObjectsAndKeys: title_data, title, thumbnail_data, thumbnail, author_data,author, nil]; [myObject addObject:dictionary]; } }
Add two datasource methods: “tableView:numberOfRowsInSection” and “tableView:cellForRowAtIndexPath”.
The first method is used to inform the table view how many rows are in the section. So let’s add the below code.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return myObject.count; }And insert cellForRowAtIndexPath ( required methods).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"Item"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell=[[UITableViewCell alloc]initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row]; NSMutableString *text; //text = [NSString stringWithFormat:@"%@",[tmpDict objectForKey:title]]; text = [NSMutableString stringWithFormat:@"%@", [tmpDict objectForKeyedSubscript:title]]; NSMutableString *detail; detail = [NSMutableString stringWithFormat:@"Author: %@ ", [tmpDict objectForKey:author]]; NSMutableString *images; images = [NSMutableString stringWithFormat:@"%@ ", [tmpDict objectForKey:thumbnail]]; NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:thumbnail]]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [[UIImage alloc]initWithData:data]; cell.textLabel.text = text; cell.detailTextLabel.text= detail; cell.imageView.frame = CGRectMake(0, 0, 80, 70); cell.imageView.image =img; return cell; }
Run your project and see the NSlog Console it's will show.
The JSON data will import to UITableView and you first iOS7 will complete!
From my iOS Dev in Thailand community : Daydev.com [All Tutorial in Thai]
Source Code available: http://www.daydev.com/source-code-web-service-ios7-uitableview
This was awesome!! Thank you!
ReplyDeleteHi there. Great. Thank you for the tutorial. One question, it seems to run extremely slowly. Any ideas why?
ReplyDeleteYeah.. It's depend on number of node of JSON, and this tutorial show the alternate way to parse JSON without any library like "JSON Read", {Sorry for my poor English}.
Deleteis there a solution to make it more smoother
Deletethank you for this helpful tutorial , please how could I put authentication info "user name , password" of my API link ?
ReplyDeleteOk, I have one solution.
Deletetry this.
- (IBAction)btnLogin:(id)sender {
NSDictionary *chk = @{ @"user":txtUsername.text, @"pass":txtPassword.text };
[self.memberService checkLogin:chk completion:^
{
if(memberService.items.count ==0)
{
UIAlertView *av =
[[UIAlertView alloc]
initWithTitle:@"Login Status"
message:@"Login Failed."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil
];
[av show];
}
else
{
/*
UIAlertView *av =
[[UIAlertView alloc]
initWithTitle:@"Login Status"
message:@"Login OK."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil
];
[av show];
*/
LoginInfoViewController *viewInfo = [[[LoginInfoViewController alloc] initWithNibName:nil bundle:nil] autorelease];
NSDictionary *item = [self.memberService.items objectAtIndex:0];
viewInfo.sid = [item objectForKey:@"id"];
[self presentViewController:viewInfo animated:NO completion:NULL];
}
}];
}
Can you explain how to make the UITableViewCell clickable with the permalink of the blog post so that it opens up in the browser.
ReplyDeleteHey guy i found some solution for UITableView "Lag" when scroll up, it's many load image from Website to show in UITableViewCell.
ReplyDeleteEdit some JSON Feed plug-in from Wordpress Web services.
in file /URL/wp-content/plugin/feed-json/template/feed-json.php
change thumbnail node replace with this code below:
// thumbnail
if (function_exists('has_post_thumbnail') && has_post_thumbnail($id)) {
$single["thumbnail"] = preg_replace("/^.*['\"](https?:\/\/[^'\"]*)['\"].*/i","$1",get_the_post_thumbnail($id,'thumbnail'));
}
// thumbnail
$news_ts = 's';
$single["news_images"] = $news_ts;
// category
Work find and without "Lag".
This is a great tutorial!! thank you so much!! I have a question about the showed items on tableview, the current table has show all the photos, title, description of those items, while i wanna show more details for each of them, it means i need to create one more view controller to show the temporary selected item's details. how can i do?
ReplyDeleteone more question@@..there are two json paths that i've created, jsonA: contains the product id, click rate only, jsonB: contains product id, description,price,url image, or anything. while i want to get the jsonA's data at first and display "the click rate message" after selecting the product on jsonA table, then it should get jsonB table to get the "description" or anything for showing the detailed infomation@@ how can i should the product id to show what i want in two json paths?
ReplyDeleteYes, you can at the line
DeleteNSData *jsonSource = [NSData dataWithContentsOfURL:
[NSURL URLWithString:@"http://gooruism.com/feed/json"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *title_data = [dataDict objectForKey:@"title"];
NSString *thumbnail_data = [dataDict objectForKey:@"thumbnail"];
NSString *author_data = [dataDict objectForKey:@"author"];
NSLog(@"TITLE: %@",title_data);
NSLog(@"THUMBNAIL: %@",thumbnail_data);
NSLog(@"AUTHOR: %@",author_data);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
title_data, title,
thumbnail_data, thumbnail,
author_data,author,
nil];
[myObject addObject:dictionary];
}
change some parameter or create callback function for get the URL.
hey, banyapon. a suggestion for you. hope you can write an article about a search bar to sort or search json data.(storyboard)
ReplyDeletehi, pak c.
DeleteJSON Webservice with UITableView and UISearchBar to filters data is done.
see this link: http://thedarkdev.blogspot.com/2014/02/xcode-uitableview-and-uisearchbar-with.html
i got crash saying "data parameter is nil".....what to do?
ReplyDeleteHi, I have got the same error, did you sort it out or not yet ?!
DeleteThe JSON is not have value because use "" than "nil" to handled this errors.
Deletein this tutorial thumbnails are nil.
Hi, thank you for your tutorial.
ReplyDeleteI cannot get this out, always I got system error message saying "Data parameter is nil"
can you help please.
Thumbnail in JSON are nil use "" to handler.
Deletei don't see my images and the image frame in my tableview, any idea what the problem is ?
ReplyDeleteI'm having the same problem. Any ideas?
DeleteStill got this problem =\
DeleteDoesn't work for me. I keep getting:
ReplyDeleteTerminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x17003de80'
i think some value is nil.
DeleteHow do i create one more label field in my cell?
ReplyDeleteYes you can, you can call uitablecell with import header file and style it,
DeleteHi ! The link to download a project is dead. Thank you
ReplyDeleteIt was fixed.
Deletehttp://www.daydev.com/source-code-web-service-ios7-uitableview
thank you it's best tutorial for me
ReplyDeleteI have a question.
how to add detail viewcontroller by using navigation control?
could you share your idea?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
Delete{
DetailNewsViewController *viewController = [[DetailNewsViewController alloc] init];
viewController.dataName=[listOfTitle objectAtIndex:indexPath.row];
viewController.dataText=[listOfDetails objectAtIndex:indexPath.row];
//viewController.dataimg=[listOfThumbnails objectAtIndex:indexPath.row];
[self.navigationController pushViewController:viewController animated:YES];
}
Thank you for your direction.
ReplyDeleteHowever when I add above code on viewcontroller.m , occurred error messages
as below:
""Invaild argument type 'void' to unary expresssion""..
Do I add additional code and view at source?
I only added navigation controller at storyboard....
I am starter programer....
I need additional description or full source code about this.
Could you send me full source for study?
Have a nice weekend.
Jin