import Foundation enum NetworkFailure { static func isCancellation(_ error: Error) -> Bool { errors(from: error).contains { error in if error is CancellationError { return true } let nsError = error as NSError return nsError.domain == NSURLErrorDomain && nsError.code == NSURLErrorCancelled } } static func isConnectionFailure(_ error: Error) -> Bool { !isCancellation(error) && errors(from: error).contains { cause in let nsError = cause as NSError guard nsError.domain == NSURLErrorDomain else { return false } switch nsError.code { case NSURLErrorNotConnectedToInternet, NSURLErrorDataNotAllowed, NSURLErrorTimedOut, NSURLErrorCannotFindHost, NSURLErrorCannotConnectToHost, NSURLErrorDNSLookupFailed, NSURLErrorNetworkConnectionLost, NSURLErrorSecureConnectionFailed, NSURLErrorInternationalRoamingOff, NSURLErrorCannotLoadFromNetwork: return true default: return false } } } static func message(for error: Error) -> String { for cause in errors(from: error) { let nsError = cause as NSError guard nsError.domain == NSURLErrorDomain else { continue } switch nsError.code { case NSURLErrorNotConnectedToInternet, NSURLErrorDataNotAllowed: return "You are not connected to the internet. Check your connection and try again." case NSURLErrorTimedOut: return "The request timed out. Try again." case NSURLErrorCannotFindHost, NSURLErrorCannotConnectToHost, NSURLErrorDNSLookupFailed, NSURLErrorNetworkConnectionLost: return "The connection to the server failed. Try again." default: continue } } return error.localizedDescription } private static func errors(from error: Error) -> [Error] { var result: [Error] = [] var current: Error? = error var seen = Set() while let cause = current, result.count < 32 { if let notSent = cause as? ActionNotSentError { result.append(cause) current = notSent.underlying continue } let nsError = cause as NSError guard seen.insert(ObjectIdentifier(nsError)).inserted else { break } result.append(cause) current = nsError.userInfo[NSUnderlyingErrorKey] as? Error } return result } }