Skip to content

Instantly share code, notes, and snippets.

@e-sung
Created January 18, 2018 05:25
Show Gist options
  • Save e-sung/869ba19eedcecf2b6ab546dcadf95a84 to your computer and use it in GitHub Desktop.
Save e-sung/869ba19eedcecf2b6ab546dcadf95a84 to your computer and use it in GitHub Desktop.
download File From Web with Alamofire
func downloadFile(from remoteURL: URL, completion: @escaping (_ localURL: URL) -> Void) {
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsDirectoryURL.appendingPathComponent(randomString)
if FileManager.default.fileExists(atPath: destinationUrl.path) {
DispatchQueue.main.async { completion(destinationUrl) }; return
}
URLSession.shared.downloadTask(with: remoteURL, completionHandler: { (location, response, error) -> Void in
guard let location = location, error == nil else { return }
do {
try FileManager.default.moveItem(at: location, to: destinationUrl)
DispatchQueue.main.async { completion(destinationUrl) }
} catch let error as NSError { print(error) }
}).resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment