Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active February 10, 2019 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/088aa8abf2e8113df22d11a939250658 to your computer and use it in GitHub Desktop.
Save robertmryan/088aa8abf2e8113df22d11a939250658 to your computer and use it in GitHub Desktop.
// method with closure that throws
func download(completion: @escaping (URL?) throws -> Void) {
let url = ...
URLSession.shared.downloadTask(with: url) { location, _, _ in
do {
try completion(location)
} catch let fileSavingError {
// Perhaps you're going to do some complicated error handling process that logs the problem or whatever.
// In this case, I'll just print the error that the `completion` closure threw.
print(fileSavingError)
}
}
}
// caller can then throw errors (notice the `try` references below) that the above method can catch
download { location in
guard let location = location else { return }
let fileURL = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
try FileManager.default.copyItem(at: location, to: fileURL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment