iOS Swift如何实现图片下载进度的获取与打印
你当前使用的Data(contentsOf: url)属于同步一次性加载数据的接口,本身不会拆分下载过程返回进度信息,无法直接获取下载进度。要实现进度打印需要改用URLSession配合代理实现,完整实现代码如下:
import UIKit class ImageDownloader: NSObject, URLSessionDownloadDelegate { private var downloadTask: URLSessionDownloadTask? func downloadImage(from url: URL) { let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue()) downloadTask = session.downloadTask(with: url) downloadTask?.resume() } // 下载进度回调 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { guard totalBytesExpectedToWrite > 0 else { return } let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) // 打印进度,保留2位小数 print(String(format: "下载进度:%.2f%%", progress * 100)) } // 下载完成回调 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { do { let data = try Data(contentsOf: location) guard let image = UIImage(data: data) else { print("图片数据解析失败") return } UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) print("图片下载完成并已保存到相册") } catch { print("下载完成后读取数据失败:\(error.localizedDescription)") } } // 下载失败回调 func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let error = error { print("下载失败:\(error.localizedDescription)") } } } // 调用示例 let imageUrl = URL(string: "https://images.unsplash.com/photo-1577771488438-6307361e4023?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=668&q=80")! let downloader = ImageDownloader() downloader.downloadImage(from: imageUrl)
适配Flutter插件时,如果需要把进度同步到Flutter层,直接在进度打印的位置通过你已注册的Flutter MethodChannel/EventChannel发送进度值即可,逻辑和Android端插件向Flutter传递事件的逻辑一致。
内容的提问来源于stack exchange,提问作者Arpit todewale
相关产品推荐
相关产品推荐

