簡體   English   中英

無法在NSURLSession委托方法中更新用戶界面

[英]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];
});

在評論馬丁的回答時, 鄧肯C問道

(I)找不到從后台線程調用NSURLSession委托方法的明確聲明。 你知道文檔是否在某處明確說明了嗎?

NSURLSession.delegateQueue文檔

與該會話相關的所有委托方法調用和完成處理程序都在此隊列上執行。

如果在創建會話時未明確設置delegateQueue

...會話創建一個串行操作隊列,用於執行所有委托方法調用和完成處理程序調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM