没有在完成块中获得响应数据

时间:2016-04-21 13:11:24

标签: ios objective-c iphone nsurlsession

我正在使用此代码向服务器发出请求。我在completionHandler块中得到了响应然后我想传递成功块但是我得到了空

-(void)getJsonResponse : (NSString *)urlStr success : (void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSURLSession *session = [NSURLSession sharedSession];

    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

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

        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"str is %@",str);

        // Convert to JSON object:
        NSError *jsonerror = nil;
        NSData *data1 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *jsondistionary = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:&jsonerror];
        NSLog(@"str is JSON ERROR %@",jsonerror);

        NSLog(@"%@", jsondistionary); here i am getting data 
        success(jsondistionary) ;
    }]resume];  
}

这是我的调用方法,我想获得响应但是得到空

[self getJsonResponse:SERVER_API_URL success:^(NSDictionary *responseDict) {

        NSLog(@"%@ responseDict ====",responseDict);
        /here i am getting null 

    } failure:^(NSError *error) {
        // error handling here ...
    }];

方法

有什么问题

1 个答案:

答案 0 :(得分:0)

首先验证您是否从您尝试发出请求的URL获得有效的JSON响应(使用某些REST客户端,例如:POSTMAN)。之后,跳过要转换为字符串的步骤,然后再次转换为数据(data1)。直接使用您在完成块中获得的数据来获取字典。

 -(void)getJsonResponse : (NSString *)urlStr success : (void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSURLSession *session = [NSURLSession sharedSession];

    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

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


        NSDictionary *jsondistionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonerror];
        NSLog(@"str is JSON ERROR %@",jsonerror);

        NSLog(@"%@", jsondistionary);
        success(jsondistionary) ;
    }]resume];


}