简体   繁体   中英

Download multiple URLs using Alamofire 5

I want to download the file from the URL Array and put the results stored in another Array.

Ex.

let urls = [URL1,URL2,URL3,....]
for url in urls {
    AF.download(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers:
    headers, interceptor: nil, to: destination).response { (responseData) in

        self.urlLoad.append(responseData.fileURL!)
        completion(self.urlLoad)

    }

}

What I am having a problem with right now is the download and get the same result. I don't know what to do. Please guide me

You haven't shared your destination , but the question is how that closure was defined and how you built the URL that was returned. But you want to give it a DownloadRequest.Destination closure that returns a unique path for each URL. For example, you can tell it to put the downloads in the “caches” folder like so:

let urls = [
    "https://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg",
    "https://spaceflight.nasa.gov/gallery/images/apollo/apollo10/hires/as10-34-5162.jpg",
    "https://spaceflight.nasa.gov/gallery/images/apollo-soyuz/apollo-soyuz/hires/s75-33375.jpg",
    "https://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-134-20380.jpg",
    "https://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-140-21497.jpg",
    "https://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-148-22727.jpg"
].compactMap { URL(string: $0) }

let folder = try! FileManager.default
    .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("images")

for url in urls {
    let destination: DownloadRequest.Destination = { _, _ in
        let fileURL = folder.appendingPathComponent(url.lastPathComponent)
        return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }

    AF.download(url, to: destination).response { responseData in
        switch responseData.result {
        case .success(let url):
            guard let url = url else { return }
            self.urlLoad.append(url)

        case .failure(let error):
            print(error)
        }
    }
}

Or, alternatively:

for url in urls {
    AF.download(url) { _, _ in
        (folder.appendingPathComponent(url.lastPathComponent), [.removePreviousFile, .createIntermediateDirectories])
    }.response { responseData in
        switch responseData.result {
        case .success(let url):
            guard let url = url else { return }
            self.urlLoad.append(url)

        case .failure(let error):
            print(error)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM