简体   繁体   中英

Can't read file when NSProgress shows complete?

I use [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response){}] to download something.

I read downloaded file when progress.fractionCompleted==1 by using KVO. And I find that something I get a nil when I read the file.

So, I want to know when I can read file. And progress complete means completely write file on disk or just receive all the data .

EDIT

- (void)URLSession:(__unused NSURLSession *)session
      downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask
      didWriteData:(__unused int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    self.progress.totalUnitCount = totalBytesExpectedToWrite;
    self.progress.completedUnitCount = totalBytesWritten;
}

So, it should be writing file first then setting progress? But why I get a nil???

It is fine to track progress in your delegate method if you want to display some sort of progress to the user. But that is not how you know when to grab the file.

The way to know when you can grab the file is when the delegate method URLSession:downloadTask:didFinishDownloadingToURL: fires. You must grab the file in that delegate method .

And you must do it immediately . You cannot use KVO in between, because in the interval between the moment the delegate method fires and the moment you are notified via KVO, the file may be destroyed. It is destroyed when we return from URLSession:downloadTask:didFinishDownloadingToURL: . That is why you must grab it inside that method, and nowhere else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM