2016-07-29 4 views
1

웹 서비스 API에서 json 응답을 얻으려고합니다. json에서 제품 데이터를 추출하고 싶습니다. 또한 AFNetworking을 사용하여 구현하고 NSURLSession을 사용하여 반응을 얻으려고 노력하고 있습니다.AFNetworking, NSURLSession 및 json 응답 (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. 

또한 다운로드 및 JSON 데모를 확인 : https://drive.google.com/open?id=0B0rS2ZVDMVRiSmJJb1BuQklJSzAClick to show JSON demo Hear

사람이하는 일이 완료되는 방법을 this.me을 할 수있는 방법을 제안 할 수 있습니다.

+0

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

답변