在 iOS 開發中,AFNetworking 是常見的網路請求工具。一般下載檔案時常使用 AFURLSessionManager,但若需要即時顯示下載百分比,可以改用 AFHTTPRequestOperation。
官方文件提到,AFHTTPRequestOperationManager 通常是建立請求的首選,但 AFHTTPRequestOperation 也可以單獨使用。若需求是下載檔案並回報進度,這個類別很適合。
常見做法如下:
[op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
CGFloat progress = (CGFloat)totalBytesRead / totalBytesExpectedToRead;
HUD.progress = progress;
}];若下載網址失效,記得替換成可測試的檔案位址。範例專案可參考:https://github.com/WorthyZhang/DownloadWithProgressBarDemo