1

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?

Nicholas
  • 1,915
  • 31
  • 55

2 Answers2

3

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!)
Khundragpan
  • 1,952
  • 1
  • 14
  • 22
1

You should download it first, then save it to a local file.

Code example can be found here: (using AFNetworking)

How I properly setup an AFNetworking Get Request?

Community
  • 1
  • 1
Hoang Tran
  • 296
  • 1
  • 6