1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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<ObjectIdentifier>()
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
}
}