- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask
*)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
float progress = (float)((float)totalBytesWritten /(float)totalBytesExpectedToWrite);
self.progressView.progress = progress;
self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress*100];
}
我正在通过 iOS 7 中添加的 NSURLSession 下载文件。到目前为止一切正常,但由于某种原因用户界面没有更新。我检查过该方法正在被调用,我也可以 NSLog 进度。
也许是因为这个方法经常被调用?但是你如何更新你的用户界面,例如如果你有一个进度条呢?提前致谢:)
最佳答案
NSURLSession 默认在后台线程中运行,因此您需要在主线程中调用您的 UI 更新。
dispatch_async(dispatch_get_main_queue(), ^{
// perform on main
float progress = (float)((float)totalBytesWritten /(float)totalBytesExpectedToWrite);
self.progressView.progress = progress;
self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress*100];
});
关于ios - 无法在 NSURLSession 委托(delegate)方法中更新用户界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21679234/