【问题标题】:Almofire multiple images Download and save them locallyAlamofire 多张图片下载并保存在本地
【发布时间】:2020-09-28 18:32:51
【问题描述】:

我有超过 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)
                }
            }
        }
    }

图像字典包含 localName 作为键 serverPath 作为值

【问题讨论】:

    标签: ios swift alamofire urlsession


    【解决方案1】:

    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
        }
    

    更新: 限制不在 AF 上,而是在 URLSession 上。一个 AF 下载器使用一个 URLSession。你必须通过自定义URLSessionConfigurations 来处理更多的活跃下载HTTPMaximumConnectionsPerHost。并将其传递给 AF Session

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      相关资源
      最近更新 更多