Download file from server using Swift

℡╲_俬逩灬. 提交于 2019-11-28 10:14:02

Xcode 8.3.2 • Swift 3.1

if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {
    // create your document folder url
    let documentsUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    // your destination file url
    let destination = documentsUrl.appendingPathComponent(audioUrl.lastPathComponent)
    print(destination)
    // check if it exists before downloading it
    if FileManager().fileExists(atPath: destination.path) {
        print("The file already exists at path")
    } else {
        //  if the file doesn't exist
        //  just download the data from your url
        URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) in
            // after downloading your data you need to save it to your destination url
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("audio"),
                let location = location, error == nil
                else { return }
            do {
                try FileManager.default.moveItem(at: location, to: destination)
                print("file saved")
            } catch {
                print(error)
            }
        }).resume()
    }
}

Xcode 10.1, Swift 4

I used the example above from @leo-dabus but broke up the code a bit into two functions. One flaw I found in that approach was that it did not handle the case where the file is already downloaded.

This example will remove any previous file that was already downloaded and write the latest version.

/// Downloads a file asynchronously
func loadFileAsync(url: URL, completion: @escaping (Bool) -> Void) {

    // create your document folder url
    let documentsUrl = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

    // your destination file url
    let destination = documentsUrl.appendingPathComponent(url.lastPathComponent)

    log.info(m: "downloading file from URL: \(url.absoluteString)")
    if FileManager().fileExists(atPath: destination.path) {
        print("The file already exists at path, deleting and replacing with latest")

        if FileManager().isDeletableFile(atPath: destination.path){
            do{
                try FileManager().removeItem(at: destination)
                print("previous file deleted")
                self.saveFile(url: url, destination: destination) { (complete) in
                    if complete{
                        completion(true)
                    }else{
                        completion(false)
                    }
                }
            }catch{
                print("current file could not be deleted")
            }
        }
    // download the data from your url
    }else{
        self.saveFile(url: url, destination: destination) { (complete) in
            if complete{
                completion(true)
            }else{
                completion(false)
            }
        }
    }
}


func saveFile(url: URL, destination: URL, completion: @escaping (Bool) -> Void){
    URLSession.shared.downloadTask(with: url, completionHandler: { (location, response, error) in
        // after downloading your data you need to save it to your destination url
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let location = location, error == nil
            else { print("error with the url response"); completion(false); return}
        do {
            try FileManager.default.moveItem(at: location, to: destination)
            print("new file saved")
            completion(true)
        } catch {
            print("file could not be saved: \(error)")
            completion(false)
        }
    }).resume()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!