2017-02-22 71 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? 
    } 

第二件事情是,你可以簡單地創建一個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]; 
} 

我建議你應該設計你的代碼爲我的建議使用block代替。