You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 10:51:00