Skip to content

Instantly share code, notes, and snippets.

@KrisYu
Created July 9, 2017 05:03
Show Gist options
  • Save KrisYu/3afc5937e50e19335fda85740f219481 to your computer and use it in GitHub Desktop.
Save KrisYu/3afc5937e50e19335fda85740f219481 to your computer and use it in GitHub Desktop.
URLSession download files
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, error == nil else { return }
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
do {
let fullURL = try documentDirectory?.appendingPathComponent((response?.suggestedFilename!)!)
try FileManager.default.moveItem(at: tempLocation, to: fullURL!)
print("saved at \(String(describing: fullURL)) ")
} catch CocoaError.fileReadNoSuchFileError {
print("No such file")
} catch {
// other errors
print("Error downloading file : \(error)")
}
}.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment