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

Ios 如何从NSURLSessionDataTask和调用块获取返回值?,ios,objective-c,block,Ios,Objective C,Block,我有一个方法,该方法返回nsdata值,但我不知道如何从NSURLSessionDataTask块获取返回值。以及如何调用getDownloadFileData方法。任务的代码是:- 来电者: NSData *getFileDataResult = [self getDownloadFileData:pathString]; 方法: - (NSData*) getDownloadFileData : (NSString*) filePath { NSURLSessionDataTas

我有一个方法,该方法返回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?
 }
有人能帮我吗


非常感谢。

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

 - (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
变量,并在completion
block
中为其赋值,而不是将
数据
传递回去

只需在完成块中这样做

if(fileData){
    return fileData;
}

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

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

我建议您应该按照我的建议设计代码,而不是使用块。

您可以使用完成块,请查看