Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AFNetworking、NSURLSession和json响应(Ronak Sankhala)_Json_Xcode_Web Services_Afnetworking_Nsurlsession - Fatal编程技术网

AFNetworking、NSURLSession和json响应(Ronak Sankhala)

AFNetworking、NSURLSession和json响应(Ronak Sankhala),json,xcode,web-services,afnetworking,nsurlsession,Json,Xcode,Web Services,Afnetworking,Nsurlsession,我试图从web服务api获取json响应。我想从json中提取产品数据。我还想使用AFNetworking实现这一点,我还试图使用NSURLSession获得响应,它完全可以工作 viewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> @property (weak

我试图从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.
viewController.h
#进口
@界面ViewController:UIViewController
@属性(弱、非原子)IBUITableView*tblTableView;
-(iAction)btnClickedPostData:(id)发送方;
@结束
viewController.m
#导入“ViewController.h”
#导入“AFNetworking.h”
#导入“ResponseTableViewCell.h”
@界面视图控制器()
{
NSMutableDictionary*dictArray;
NSMutableArray*数据阵列;
}
@结束
@实现视图控制器
静态NSString*CellIdentifier=@“cell”;
-(无效)viewDidLoad{
[超级视图下载];
[self.tblTableView注册表项nb:[UINib nibWithNibName:@“ResponseTableViewCell”捆绑包:nil]forCellReuseIdentifier:@“ResponseTableViewCell”];
[自连接字符串];
}
-(无效)连接字符串
{
//NSURL*URL=[NSURL URLWithString:@“您的URL]”;
NSURLSession*会话=[NSURLSession sharedSession];//其工作状态
NSURLSessionDataTask*dataTask=[session dataTaskWithURL:[NSURL URLWithString:@“您的URL”]completionHandler:^(NSData*数据,NSURLRResponse*响应,NSError*错误){
NSMutableDictionary*jsonResponse=[NSJSONSerialization JSONObjectWithData:数据选项:0错误:无];
NSLog(@“%@”,jsonResponse);
dataArray=[jsonResponse objectForKey:@“objEventcategoryList”];
self.tblTableView.dataSource=self;
self.tblTableView.delegate=self;
[self.tblTableView reloadData];
NSLog(@“JSON:%@”,数据数组);
}];
[数据任务恢复];
//AFHTTPSessionManager*manager=[AFHTTPSessionManager];//工作正常
//[管理员获取:URL.absoluteString参数:无进度:无成功:^(NSURLSessionTask*任务,id响应对象){
//        
//NSMutableDictionary*jsonResponse=(NSMutableDictionary*)responseObject;
//dataArray=[jsonResponse objectForKey:@“objEventcategoryList”];
//        
//self.tblTableView.dataSource=self;
//self.tblTableView.delegate=self;
//        
//[self.tblTableView reloadData];
//        
//NSLog(@“TableView:%@”,tblTableView);
//        
//        
//NSLog(@“JSON:%@”,数据数组);
//}失败:^(NSURLSessionTask*操作,NSError*错误){
//NSLog(@“错误:%@”,错误);
//    }];
}
#布拉格马克酒店
#pragma marrk-TableView数据源和Deleget
#布拉格马克酒店
-(NSInteger)表视图:(UITableView*)表视图行数节:(NSInteger)节
{
返回[dataArray count];//它不工作
}
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
ResponseTableViewCell*单元格=(ResponseTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@“ResponseTableViewCell”];
dictArray=[dataArray objectAtIndex:indexath.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;
返回单元;
}
-(void)tableView:(UITableView*)tableView将显示单元格:(UITableViewCell*)用于rowatindexpath的单元格:(NSIndexPath*)indexPath{
if([tableView respondsToSelector:@selector(setSeparatorInset:)]))
{
[表视图集合分割集:UIEdgeInsetsZero];
}
if([tableView respondsToSelector:@selector(setLayoutMargins:)]))
{
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if([cell respondsToSelector:@selector(setLayoutMargins:)]))
{
[单元格设置布局边距:UIEdgeInsetsZero];
}
}
-(CGFloat)tableView:(UITableView*)表视图行高度索引路径:(NSIndexPath*)索引路径
{
回报率144.0;
}
-(无效)未收到记忆警告{
[超级记忆警告];
//处置所有可以重新创建的资源。
}
-(iAction)btnClickedPostData:(id)发件人{
NSString*tokenString=@“65d188d3f0ab52487001c331584ac819”;
NSURLSessionConfiguration*defaultConfigObject=[NSURLSessionConfiguration defaultSessionConfiguration];
[defaultConfigObject setHTTPAdditionalHeaders:@{@“token”:tokenString}];
NSURLSession*defaultSession=[NSURLSession sessionWithConfiguration:defaultConfigObject委托:无委托队列:[NSOperationQueue mainQueue]];
NSURL*url=[NSURL URLWithString:@“您的url]”;
NSString*paramString=@“lang=en&title=&start=&end=”;
NSData*httpBody=[paramString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest*urlRequest=[NSMutableUrlRequestWithURL:url];
[UrlRequestSetTimeOutInterval:60.0];
NSString*msgLength=[NSString stringWithFormat:@“%lu”,无符号长)[httpBody长度]];
[urlRequest addValue:@“应用程序/x-www-form-urlencoded”forHTTPHeaderField:@“内容类型”];
[URLRESQUEST addValue:msgLength forHTTPHeaderField:@“内容长度”];
[urlRequestSetHttpMethod:@“POST”];
//[urlRequest setAllHTTPHeaderFields:paramString];
[urlRequestSetAllHttpHeaderFields:@{@“token”:tokenString}];
[urlRequestSetHttpBody:httpBody];
//[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding];
NSURLSessionDataTask*dataTask=[defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData*数据,NSURLRResponse*响应,NSError*错误)
{
NSError*parseError=nil;
NSHTTPURLResponse*respHttp=(NSHTTPURLResponse*)响应;
如果(!error&&respHttp.statusCode==200){
NSDictionary*responseDictionary=[NSJSONSerialization JSONObjectWithData:数据选项:0错误:&parseError];
NSMutableArray*Arraray=[responseDictionary objectForKey:@“新闻列表”];
NSString*title=[NSString stringWithFormat:@“%@,[arrArray valueForKey:@“title”];
UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@“详细信息”消息:title委托