如何使用NSURLSession从块获取数据?

时间:2014-10-03 07:12:13

标签: ios objective-c objective-c-blocks nsurlsession

我对这个块有问题。我试图将数据放在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的块中获取数据?

4 个答案:

答案 0 :(得分:27)

-(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 ... 
}];

答案 1 :(得分:8)

您应该使用完成块,例如:

- (void)retrieveData:(void (^)(NSDictionary * dictionary))completionHandler {
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString: self.getURL];

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        if (completionHandler) {
            completionHandler(dictionary);
        }
    }];
    [dataTask resume];
}

然后调用它的方法会:

[self retrieveData:^(NSDictionary *dictionary) {
    // you can use the dictionary here

    // if you want to update UI or model, dispatch this to the main queue:
     dispatch_async(dispatch_get_main_queue(), ^{
         // do your UI stuff here
     });
}];

// but dont try to use the dictionary here, because you will likely
// hit this line before the above block fires off, and thus the 
// dictionary hasn't been returned yet!

您正在调用采用完成块模式的异步方法,因此您还应该在自己的代码中使用完成块模式。

答案 2 :(得分:3)

你必须了解这种方法。最好将您的方法从RetrieveData重命名(您在这里违反了Cocoa命名约定)到startRetrievingData。您无法编写实际检索数据的方法,因为在最坏的情况下可能需要几分钟,而您的用户会讨厌您。

将其命名为startRetrievingData,使其返回void,并传入两个块,这将在将来检索数据时调用,并且在将来发生错误时将调用,并且您可以得不到数据。

您无法返回数据。不要问“我如何返回数据”,你就是不能。您为代码提供了一个在数据可用时调用的块,并且该块负责处理数据,无论您想用它做什么。

答案 3 :(得分:1)

NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"http://www.code-brew.com/projects/Instamigos/api/login.php?instagram_id=572275360&access_token=572275360.4c70214.57e0ecb1113948c2b962646416cc0a18&name=dpak_29&uuid=ios_1"];
// Asynchronously API is hit here
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {    
                                             NSLog(@"%@",data);
                                             // Executed when the response comes from server

                                             // Handle Response here
                                             NSDictionary * json  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                                             NSLog(@"%@",json);
}];
[dataTask resume];   // Executed First