Nicholas Nicholas - 4 months ago 67
Swift Question

How to copy remote server file in document directory in swift

I know how to get a remote URL in Swift

let remoteURL = NSURL(string: "https://myserver/file.txt")!


I know how to get a local URL in Swift

let localURL = NSURL(fileURLWithPath: documentsFolder + "/my_local_file.txt")


and unfortunately this does not work

NSFileManager.defaultManager().copyItemAtURL(remoteURL, toURL: localURL)


with the following error

The file “file.txt” couldn’t be opened because URL type https isn’t supported.


Is there a way how to perform this?

Answer

You can use NSURLSessionDownloadTask to download the file:

func downloadFile(url: URL) {
    let downloadRequest = URLRequest(url: url)
    URLSession.shared.downloadTask(with: downloadRequest) { location, response, error in
        // To do check resoponse before saving
        guard  let tempLocation = location where error == nil else { return }
        let documentDirectory = FileManager.default.urlsForDirectory(.documentDirectory, inDomains: .userDomainMask).last
        do {
            let fullURL = try documentDirectory?.appendingPathComponent((response?.suggestedFilename!)!)
            try FileManager.default.moveItem(at: tempLocation, to: fullURL!)
            print("saved at \(fullURL) ")
        } catch NSCocoaError.fileReadNoSuchFileError {
            print("No such file")
        } catch {
            // other errors
            print("Error downloading file : \(error)")
        }
    }.resume()
}

let stringURL = "https://wordpress.org/plugins/about/readme.txt"
downloadImage(url: URL(string: stringURL)!)

Update: SWIFT 2.2

func downloadFile(url: NSURL) {
    let downloadRequest = NSURLRequest(URL: url)
    NSURLSession.sharedSession().downloadTaskWithRequest(downloadRequest){ (location, response, error) in

        guard  let tempLocation = location where error == nil else { return }
        let documentDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
        let fullURL = documentDirectory?.URLByAppendingPathComponent((response?.suggestedFilename)!)

        do {
            try NSFileManager.defaultManager().moveItemAtURL(tempLocation, toURL: fullURL!)
        } catch NSCocoaError.FileReadNoSuchFileError {
            print("No such file")
        } catch {
            print("Error downloading file : \(error)")
        }

        }.resume()
}

 let stringURL = "https://wordpress.org/plugins/about/readme.txt"
 let url = NSURL.init(string: stringURL)
 downloadFile(url!)