Created
July 9, 2017 05:03
-
-
Save KrisYu/3afc5937e50e19335fda85740f219481 to your computer and use it in GitHub Desktop.
URLSession download files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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