2017-02-22 20 views
0

私はメソッドを持っていますが、メソッドはnsdataの値を返していますが、NSURLSessionDataTaskブロックから戻り値を取得する方法はわかりません。そしてどのようにタスクのためgetDownloadFileData methods.Codeを呼び出すことです: -NSURLSessionDataTaskと呼び出しブロックから戻り値を取得する方法は?

、発信者:

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? 
} 

は誰もが私に手を与えることができていますか?

ありがとうございました。

+0

完了ブロックを使用するには、http://stackoverflow.com/questions/21436831/how-to-write-an-objective-c-completion-blockをご覧ください。 – raki

答えて

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? 
    } 

2つ目は、あなたは、単にNSData変数を作成し、完了blockではなくdataバックを渡すには、それを値を割り当てることができます。

OR

単に私の答えを確認してください完了ブロック

if(fileData){ 
    return fileData; 
} 
0

で、このように行う、私はあなたが私のようにコードを設計する必要がありお勧めしますこの便利

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

を願っています代わりにブロックを使用することをお勧めします。

関連する問題