简体   繁体   English

NSProgress显示完成时无法读取文件?

[英]Can't read file when NSProgress shows complete?

I use [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response){}] to download something. 我使用[manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response){}]进行下载。

I read downloaded file when progress.fractionCompleted==1 by using KVO. 我使用KVO读取了当progress.fractionCompleted == 1时下载的文件。 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. 知道何时可以获取文件的方法是何时触发委托方法URLSession:downloadTask:didFinishDownloadingToURL: 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. 您不能在两者之间使用KVO,因为在从代理方法触发到通过KVO通知您的那一刻之间,文件可能会被破坏。 It is destroyed when we return from URLSession:downloadTask:didFinishDownloadingToURL: . 当我们URLSession:downloadTask:didFinishDownloadingToURL: 返回时,它被销毁。 That is why you must grab it inside that method, and nowhere else. 这就是为什么您必须该方法内部而不是其他地方使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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