[英]Can't update user interface in NSURLSession delegate methods
- (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];
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.