如何从NSURLSessionDataTask获取返回值并调用块?

时间:2017-02-22 06:48:29

标签: ios objective-c block

我有一个方法,该方法返回了nsdata值,但我不知道如何从NSURLSessionDataTask块获取返回值。以及如何调用getDownloadFileData方法。任务的代码是: -

来电者:

 NSData *getFileDataResult = [self getDownloadFileData:pathString];

方法:

 - (NSData*) getDownloadFileData : (NSString*) filePath {

  NSURLSessionDataTask *downloadFile = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:filePath] completionHandler:^(NSData *fileData, NSURLResponse *response, NSError *error){
// .....
//  fileData should return out.

  [downloadFile resume];
  });
  // I want to return the fileData after download completion.
  // how to return?
 }

有人可以帮我一把吗?

非常感谢。

2 个答案:

答案 0 :(得分:1)

请检查我的答案,希望这有用

- (NSData *)getDownloadFileData:(NSString *)filePath {
    __block NSData *responseData = nil;

    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSURLSessionDataTask *downloadFile = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:filePath] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        responseData = data;
        dispatch_semaphore_signal(sema);
    }];
    [downloadFile resume];

    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

    return responseData;
}

- (void)whereToCall {
    // Because to prevent the semaphore blocks main thread
    dispatch_queue_t myQueue = dispatch_queue_create("com.abc", 0);
    dispatch_async(myQueue, ^{
        NSData *data = [self getDownloadFileData:@"urlString"];
    });
}

- (void)betterGetDownloadFileData:(NSString *)filePath completion:(void (^)(NSData * __nullable data))completion {
    NSURLSessionDataTask *downloadFile = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:filePath] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (completion) {
            completion(data);
        }
    }];
    [downloadFile resume];
}

我建议您应该将代码设计为我的建议,即使用阻塞。

答案 1 :(得分:0)

首先,你把简历方法放在错误的地方。它应该是这样的:

 - (NSData*) getDownloadFileData : (NSString*) filePath {
    NSURLSessionDataTask *downloadFile = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:filePath] completionHandler:^(NSData *fileData, NSURLResponse *response, NSError *error){
    // .....
    //  fileData should return out.


      });
[downloadFile resume];//NOTICE THE PLACEMENT HERE
      // I want to return the fileData after download completion.
      // how to return?
     }

第二件事是,您只需创建一个NSData变量,并在完成block中为其指定值,而不是将data传递回来。

只需在完成块中执行此操作

if(fileData){
    return fileData;
}