Skip to content

Commit 2be41e7

Browse files
authored
Merge pull request #9 from lukasz-pomianek/feature/add-no-internet-connection-handler
Added error handler so user can respond to a specific error different…
2 parents 9f5c0a4 + 65092b7 commit 2be41e7

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Sources/WebRequest/Delivery/HTTPWebRequestDelivery.swift

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,21 +103,28 @@ open class HTTPWebRequestDelivery : NSObject, WebRequestDelivery {
103103
let group = DispatchGroup()
104104
var taskData: Data?
105105
var taskResponse: HTTPURLResponse?
106+
var errorCode: ErrorCode?
106107

107108
group.enter()
108109
queue.async {
109110
let task = urlSession.dataTask(
110111
with: urlRequest,
111-
completionHandler: ({ (data, response, _) in
112+
completionHandler: ({ (data, response, error) in
112113
taskData = data
113114
taskResponse = response as? HTTPURLResponse
115+
errorCode = self.parseError(error)
114116
group.leave()
115117
}))
116118
task.resume()
117119
}
118120

119121
let timeoutResult = group.wait(timeout: .now() + timeoutInterval)
120122

123+
if let errorCode = errorCode {
124+
try complete(request: request, errorCode: errorCode)
125+
return
126+
}
127+
121128
guard (timeoutResult != .timedOut) else {
122129
try complete(request: request, errorCode: .TimedOut)
123130
return
@@ -150,4 +157,19 @@ open class HTTPWebRequestDelivery : NSObject, WebRequestDelivery {
150157
let result = WebRequest.Result(status: status, headers: [:] , data: nil)
151158
try request.onDataReceived?(result, request, percentComplete, target);
152159
}
160+
161+
open func parseError(_ error: Error?) -> ErrorCode? {
162+
guard let error = error else { return nil }
163+
if let urlError = error as? URLError {
164+
switch urlError.code {
165+
case .notConnectedToInternet:
166+
return .NoInternetConnection
167+
case .timedOut:
168+
return .TimedOut
169+
default:
170+
()
171+
}
172+
}
173+
return .MalformedResponse
174+
}
153175
}

Sources/WebRequest/WebRequest+Result.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ extension WebRequest {
1212
case MalformedURL = -8
1313
case MalformedResponse = -11
1414
case TimedOut = -12
15+
case NoInternetConnection = -13
1516
}
1617

1718
public init(status: Int) {

0 commit comments

Comments
 (0)