如何解决Almofire多张图片下载并保存到本地
我有500多个图像链接,我想下载这些图像并在应用程序启动时本地存储在应用程序文档目录中。我正在使用Almofire下载,但出现了类似的错误 “ URLSession任务已取消”,并请求超时
func downloadAllImages(images:[String: String],retryCount: Int = 0,completion: @escaping((Bool)->Void)){
var success: Bool = true
var failedImages = [String: String]()
for (localName,severPath) in images {
self.dispatchGroup.enter()
let destination: DownloadRequest.Destination = { _,_ in
let documentsURL = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent(localName)
return (fileURL,[.removePreviousFile,.createIntermediateDirectories])
}
let path = severPath.replacingOccurrences(of: "\\",with: "/").addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
//AF.sessionConfiguration.httpShouldSetCookies = false
AF.download(path,to: destination).response { response in
switch response.result {
case .success(_):
break
case .failure(let error):
if response.response?.statusCode != 404 {
success = false
failedImages[localName] = path
print("Image Download Error = \(error.localizedDescription)")
}
break
}
debugPrint(response)
self.dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
//retry If some Images failed to download
if failedImages.isEmpty || retryCount >= self.maximumRetryCount {
completion(success)
}else {
self.downloadAllImages(images: failedImages,retryCount: retryCount + 1) { (success) in
completion(success)
}
}
}
}
images词典包含 localName作为键 serverPath作为值
解决方法
AFImageDownloaders的活动下载有限制,我相信更改maximumActiveDownloads
或您的API中的类似内容都可以解决此问题。新的下载只会取消以前的下载。但是最好分块下载它们。
例如,这个用于ImageDownloader
public init(session: Session,downloadPrioritization: DownloadPrioritization = .fifo,maximumActiveDownloads: Int = 4,imageCache: ImageRequestCache? = AutoPurgingImageCache()) {
precondition(!session.startRequestsImmediately,"Session must set `startRequestsImmediately` to `false`.")
self.session = session
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
UPD:
限制不是自动对焦,而是URLSession
。一个AF下载器使用一个URLSession
。您必须通过自定义URLSessionConfigurations
来处理更多活动下载HTTPMaximumConnectionsPerHost
。并通过AF Session
类
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。