AFNetworking、NSURLSession 和 json 响应 (Ronak Sankhala)
Posted
技术标签:
【中文标题】AFNetworking、NSURLSession 和 json 响应 (Ronak Sankhala)【英文标题】:AFNetworking, NSURLSession and json Response (Ronak Sankhala) 【发布时间】:2016-07-29 10:34:32 【问题描述】:我正在尝试从 Web 服务 api 获取 json 响应。我想从 json 中提取产品数据。我还想使用 AFNetworking 来实现这一点,并且我还尝试使用 NSURLSession 获得响应,并且它完全可以工作。
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
任何人都可以建议一种方法来做到这一点。我将如何完成这些事情。
【问题讨论】:
drive.google.com/folderview?id=0B0rS2ZVDMVRiUm9IVlFlTndGRDA 【参考方案1】:You Can use also use sqlite for the data.
【讨论】:
以上是关于AFNetworking、NSURLSession 和 json 响应 (Ronak Sankhala)的主要内容,如果未能解决你的问题,请参考以下文章
AFNetworking、NSURLSession 和 json 响应 (Ronak Sankhala)
AFNetworking/NSURLSession耗时长创建100多个任务下载文件
下载许多文件时 AFNetworking / NSURLSession 超时
使用 NSURLSession 复制 AFNetworking POST 请求