The Dark Dev Team. Powered by Blogger.

Web Service Apps in iOS7 JSON with UITableView in XCode5

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] 
First my JSON Data is something like that...
[
  {
   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"
              ]
  }
]
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.
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 name



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:

#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



32 comments:

  1. Hi there. Great. Thank you for the tutorial. One question, it seems to run extremely slowly. Any ideas why?

    ReplyDelete
    Replies
    1. Yeah.. 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}.

      Delete
    2. is there a solution to make it more smoother

      Delete
  2. thank you for this helpful tutorial , please how could I put authentication info "user name , password" of my API link ?

    ReplyDelete
    Replies
    1. Ok, I have one solution.
      try 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];
      }
      }];



      }

      Delete
  3. hi..Im college student, thanks for sharing :)

    ReplyDelete
  4. Can you explain how to make the UITableViewCell clickable with the permalink of the blog post so that it opens up in the browser.

    ReplyDelete
  5. Hey guy i found some solution for UITableView "Lag" when scroll up, it's many load image from Website to show in UITableViewCell.

    Edit 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".

    ReplyDelete
  6. 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?

    ReplyDelete
  7. one 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?

    ReplyDelete
    Replies
    1. Yes, you can at the line
      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];
      }

      change some parameter or create callback function for get the URL.

      Delete
  8. hey, banyapon. a suggestion for you. hope you can write an article about a search bar to sort or search json data.(storyboard)

    ReplyDelete
    Replies
    1. hi, pak c.
      JSON 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

      Delete
  9. i got crash saying "data parameter is nil".....what to do?

    ReplyDelete
    Replies
    1. Hi, I have got the same error, did you sort it out or not yet ?!

      Delete
    2. The JSON is not have value because use "" than "nil" to handled this errors.
      in this tutorial thumbnails are nil.

      Delete
  10. Hi, thank you for your tutorial.

    I cannot get this out, always I got system error message saying "Data parameter is nil"

    can you help please.

    ReplyDelete
    Replies
    1. Thumbnail in JSON are nil use "" to handler.

      Delete
  11. i don't see my images and the image frame in my tableview, any idea what the problem is ?

    ReplyDelete
  12. Doesn't work for me. I keep getting:

    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x17003de80'

    ReplyDelete
  13. How do i create one more label field in my cell?

    ReplyDelete
    Replies
    1. Yes you can, you can call uitablecell with import header file and style it,

      Delete
  14. Hey....This is really nice..Thanks for sharing the content with us!!

    Want to know the latest and hottest trends on Twitter, then come up with the amazing app

    https://itunes.apple.com/us/app/tweet-cinema/id866641393?mt=8

    Believe me guys this is one of the best app to remain always connected with the twitter and the most interesting part, it is available absolutely free of cost!!

    Love to hear from you more about these apps!!

    ReplyDelete
  15. Hi ! The link to download a project is dead. Thank you

    ReplyDelete
    Replies
    1. It was fixed.
      http://www.daydev.com/source-code-web-service-ios7-uitableview

      Delete
  16. thank you it's best tutorial for me
    I have a question.
    how to add detail viewcontroller by using navigation control?
    could you share your idea?

    ReplyDelete
    Replies
    1. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
      {
      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];
      }

      Delete
  17. Thank you for your direction.
    However 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

    ReplyDelete

About

Daydev Co., Ltd. Thailand Outsources Service and IT Solution.

About