Tepmnthar Tepmnthar - 1 year ago 81
iOS Question

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.


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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download