Friday, 14 October 2016

Simple JSON GET Method using NSURLSession Method and NSURLSessionConfiguration (Updated).

Step 1:

In ViewController.h 

Firstly to declare the NSMutableURLRequest, NSURLSession,  NSURLSessionConfiguration, NSDictionary, NSURLSessionDataTask


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property NSMutableURLRequest *uelRequest;
@property NSURLSession *session;
@property NSURLSessionConfiguration *conifg;
@property NSDictionary *dictionaryForData;
@property NSURLSessionDataTask *dataTask;
@property (strong, nonatomic) IBOutlet UITableView *tableViewForNames;
@end


In ViewController.m 



#import "ViewController.h"

@interface ViewController () {
    NSInteger i;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    i=0;

    self.uelRequest=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"https://itunes.apple.com/in/rss/toppaidapplications/limit=100/json"]];
    
    self.conifg=[NSURLSessionConfiguration defaultSessionConfiguration];

    self.session=[NSURLSession sessionWithConfiguration:self.conifg];

    self.dataTask=[self.session dataTaskWithRequest:self.uelRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
    self.dictionaryForData=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
     NSLog(@"%@",[[[[[self.dictionaryForData valueForKey:@"feed"]valueForKey:@"entry"]objectAtIndex:0]valueForKey:@"im:name"]valueForKey:@"label"]);
     }];

     [self.dataTask resume];
     // Do any additional setup after loading the view, typically from a nib.
}


Step3:

To Display the data in TableView.


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   if (self.dictionaryForData.count>0)  {
         i=[[[self.dictionaryForData valueForKey:@"feed"]valueForKey:@"entry"] count];
    NSLog(@"%lu..........",i);
   }
   return i;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell=[[UITableViewCell alloc]init];
    cell.textLabel.text=[[[[[self.dictionaryForData valueForKey:@"feed"]valueForKey:@"entry"]objectAtIndex:indexPath.row]valueForKey:@"im:name"]valueForKey:@"label"];
    return cell;
}
@end

No comments:

Post a Comment