2016-07-29 27 views
1

Ich versuche, JSON-Antwort von einem Web-Service API zu bekommen. Ich möchte Produktdaten aus dem JSON extrahieren. Ich möchte dies auch mit AFNetworking implementieren, und ich versuche auch, Antwort mit NSURLSession zu bekommen und es funktioniert vollständig.AFNetworking, NSURLSession und JSON Antwort (Ronak Sankhala)

viewController.h 

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> 
@property (weak, nonatomic) IBOutlet UITableView *tblTableView; 

- (IBAction)btnClickedPostData:(id)sender; 



@end 

viewController.m 

#import "ViewController.h" 
#import "AFNetworking.h" 
#import "ResponseTableViewCell.h" 

@interface ViewController() 
{ 
NSMutableDictionary *dictArray; 
NSMutableArray *dataArray; 
} 

@end 

@implementation ViewController 
static NSString *CellIdentifier = @"cell"; 
- (void)viewDidLoad { 
[super viewDidLoad]; 

[self.tblTableView registerNib:[UINib nibWithNibName:@"ResponseTableViewCell" bundle:nil] forCellReuseIdentifier:@"ResponseTableViewCell"]; 
[self connectionString]; 
} 

-(void)connectionString 
{ 
//NSURL *URL = [NSURL URLWithString:@"Your URL"]; 

NSURLSession *session = [NSURLSession sharedSession]; // its working 


NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"YOUR URL"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

NSMutableDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
    NSLog(@"%@", jsonResponse); 

    dataArray = [jsonResponse objectForKey:@"objEventcategoryList"]; 

    self.tblTableView.dataSource = self; 
    self.tblTableView.delegate = self; 

    [self.tblTableView reloadData]; 


    NSLog(@"JSON: %@", dataArray); 

}]; 

[dataTask resume]; 

// AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // its working 
// [manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) { 
//   
//  NSMutableDictionary *jsonResponse = (NSMutableDictionary *)responseObject; 

//  dataArray = [jsonResponse objectForKey:@"objEventcategoryList"]; 
//   
//  self.tblTableView.dataSource = self; 
//  self.tblTableView.delegate = self; 
//   
//  [self.tblTableView reloadData]; 
//   
//  NSLog(@"TableView: %@", _tblTableView); 
//   
//   
//  NSLog(@"JSON: %@", dataArray); 
// } failure:^(NSURLSessionTask *operation, NSError *error) { 
//  NSLog(@"Error: %@", error); 
// }]; 
} 

#pragma marrk 
#pragma marrk - TableView DataSource and Deleget 
#pragma marrk 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
return [dataArray count];// its not working 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
ResponseTableViewCell *cell = (ResponseTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ResponseTableViewCell"]; 

dictArray = [dataArray objectAtIndex:indexPath.row]; 
//cell.lblCatID.text = [dictArray objrct:@""]; 
cell.lblCatID.text = [NSString stringWithFormat:@"%@", [dictArray valueForKey:@"EventCategoryId"]]; 
cell.lblEventName.text = [NSString stringWithFormat:@"%@", [dictArray valueForKey:@"EventCategoryName"]]; 
cell.lblCreateDate.text = [NSString stringWithFormat:@"%@", [dictArray valueForKey:@"CreatedDate"]]; 

cell.layoutMargins = UIEdgeInsetsZero; 

return cell; 
} 

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ 

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) 
{ 
    [tableView setSeparatorInset:UIEdgeInsetsZero]; 
} 

if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) 
{ 
    [tableView setLayoutMargins:UIEdgeInsetsZero]; 
} 

if ([cell respondsToSelector:@selector(setLayoutMargins:)]) 
{ 
    [cell setLayoutMargins:UIEdgeInsetsZero]; 
} 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
return 144.0; 
} 


- (void)didReceiveMemoryWarning { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated. 
} 

- (IBAction)btnClickedPostData:(id)sender { 

NSString *tokenString = @"65d188d3f0ab52487001c331584ac819"; 

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; 

[defaultConfigObject setHTTPAdditionalHeaders:@{ @"token" : tokenString}]; 

NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:nil delegateQueue:[NSOperationQueue mainQueue]]; 

NSURL *url = [NSURL URLWithString:@"YOUR URL"]; 
NSString *paramString = @"lang=en&title=&start=&end="; 
NSData *httpBody = [paramString dataUsingEncoding:NSUTF8StringEncoding]; 
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; 
[urlRequest setTimeoutInterval:60.0]; 
NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[httpBody length]]; 

[urlRequest addValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[urlRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"]; 
[urlRequest setHTTPMethod:@"POST"]; 
//[urlRequest setAllHTTPHeaderFields:paramString]; 
[urlRequest setAllHTTPHeaderFields:@{ @"token" : tokenString}]; 
[urlRequest setHTTPBody:httpBody]; 
//[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; 

NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
{ 
    NSError *parseError = nil; 
    NSHTTPURLResponse* respHttp = (NSHTTPURLResponse*) response; 

    if (!error && respHttp.statusCode == 200) { 
     NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; 
     NSMutableArray *arrArray = [responseDictionary objectForKey:@"newslist"]; 

     NSString *title = [NSString stringWithFormat:@"%@", [arrArray valueForKey:@"title"]]; 

     UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Details" message:title delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil]; 

     [alert show]; 

     NSLog(@"%@", arrArray); 
    }else{ 

     NSLog(@"%@", error); 
    } 

}]; 
[dataTask resume]; 

} 
@end 

//CustomeTableviewCell With XIB 
**ResponseTableViewCell.h** 

#import <UIKit/UIKit.h> 

@interface ResponseTableViewCell : UITableViewCell 
@property (weak, nonatomic) IBOutlet UILabel *lblCatID; 
@property (weak, nonatomic) IBOutlet UILabel *lblEventName; 
@property (weak, nonatomic) IBOutlet UILabel *lblCreateDate; 

@end 

**ResponseTableViewCell.m** 
#import "ResponseTableViewCell.h" 

@implementation ResponseTableViewCell 
@synthesize lblCatID,lblEventName,lblCreateDate; 
- (void)awakeFromNib { 
[super awakeFromNib]; 
// Initialization code 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 
[super setSelected:selected animated:animated]; 

// Configure the view for the selected state 
} 

@end 

// and also download and check JSON demo : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzA[Click to show JSON demo Hear][1] 

//add custom table view cell with custom table cell and add label to display information. i used pod to setup AFNetworking. 

und auch herunterladen und überprüfen Demo JSON: https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzAClick to show JSON demo Hear

Kann jemand einen Weg vorschlagen this.me, wie die Dinge getan werden zu tun.

+0

https://drive.google.com/folderview?id=0B0rS2ZVDMVRiUm9IVlFlTndGRDA –

Antwort