本文介绍了如何使用NSURLSession从块获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个块有问题。我试图获取 NSURLSession 块内的数据。

I have problem with this block. I trying to get the data inside the block of NSURLSession.

这里是我的代码

-(NSDictionary *) RetrieveData{

    NSURLSession * session = [NSURLSession sharedSession];
    NSURL * url = [NSURL URLWithString: self.getURL];
    dataList =[[NSDictionary alloc] init];

    NSURLSessionDataTask * dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        self.json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    }];
    return self.dataList;
    [dataTask resume];

}

是否有可能获取 NSURLSession

推荐答案

-(void)getJsonResponse:(NSString *)urlStr success:(void (^)(NSDictionary *responseDict))success failure:(void(^)(NSError* error))failure
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:urlStr];   

    // Asynchronously API is hit here
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {            
                                                NSLog(@"%@",data);
                                                if (error)
                                                    failure(error);
                                                else {                                               
                                                    NSDictionary *json  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                                    NSLog(@"%@",json);
                                                    success(json);                                               
                                                }
                                            }];
    [dataTask resume];    // Executed First
}

调用此:

[self getJsonResponse:@"Enter your url here" success:^(NSDictionary *responseDict) {   
        NSLog(@"%@",responseDict);
    } failure:^(NSError *error) {
        // error handling here ... 
}];

这篇关于如何使用NSURLSession从块获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 21:39