Skip to content

Instantly share code, notes, and snippets.

@Mackarous
Last active June 15, 2020 07:14
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 Mackarous/b11e8c97fa8875de30ec1a8b64edd701 to your computer and use it in GitHub Desktop.
Save Mackarous/b11e8c97fa8875de30ec1a8b64edd701 to your computer and use it in GitHub Desktop.
Handy extension on DataTaskPublisher
extension URLSession.DataTaskPublisher {
func tryFilter(httpStatusCode: Int) -> Publishers.TryFilter<Self> {
tryFilter(httpStatusCodes: httpStatusCode..<httpStatusCode+1)
}
func tryFilter(httpStatusCodes: Range<Int>) -> Publishers.TryFilter<Self> {
tryFilter(httpStatusCodes: ClosedRange(httpStatusCodes))
}
func tryFilter(httpStatusCodes: ClosedRange<Int>) -> Publishers.TryFilter<Self> {
tryFilter { data, response in
guard let httpResponse = response as? HTTPURLResponse, httpStatusCodes ~= httpResponse.statusCode else {
throw URLError(.badServerResponse)
}
return true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment