Skip to content

Commit

Permalink
Merge pull request WeTransfer#26 from WeTransfer/feature/delay-cancel…
Browse files Browse the repository at this point in the history
…lations

Correctly handle cancellation of delayed responses
  • Loading branch information
AvdLee authored Aug 13, 2019
2 parents 015c658 + aaa759c commit 9d4d60c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
1 change: 1 addition & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
### Next
- A new completion callback can be set on `Mock` to use for expectation fulfilling once a `Mock` is used.
- Updated to Swift 5.0
- Correctly handle cancellation of delayed responses

### 1.3.0
- Updated to Swift 4.2
Expand Down
13 changes: 9 additions & 4 deletions Sources/MockingURLProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public final class MockingURLProtocol: URLProtocol {
case missingMockedData(url: String)
}

private var responseWorkItem: DispatchWorkItem?

/// Returns Mocked data based on the mocks register in the `Mocker`. Will end up in an error when no Mock data is found for the request.
override public func startLoading() {
guard
Expand All @@ -27,8 +29,9 @@ public final class MockingURLProtocol: URLProtocol {
client?.urlProtocol(self, didFailWithError: Error.missingMockedData(url: String(describing: request.url?.absoluteString)))
return
}

DispatchQueue.global(qos: DispatchQoS.QoSClass.background).asyncAfter(deadline: .now() + (mock.delay ?? DispatchTimeInterval.seconds(0))) {

self.responseWorkItem = DispatchWorkItem(block: { [weak self] in
guard let self = self else { return }
if let redirectLocation = data.redirectLocation {
self.client?.urlProtocol(self, wasRedirectedTo: URLRequest(url: redirectLocation), redirectResponse: response)
} else {
Expand All @@ -38,12 +41,14 @@ public final class MockingURLProtocol: URLProtocol {
}

mock.completion?()
}
})

DispatchQueue.global(qos: DispatchQoS.QoSClass.background).asyncAfter(deadline: .now() + (mock.delay ?? DispatchTimeInterval.seconds(0)), execute: responseWorkItem!)
}

/// Implementation does nothing, but is needed for a valid inheritance of URLProtocol.
override public func stopLoading() {
// No implementation needed
responseWorkItem?.cancel()
}

/// Simply sends back the passed request. Implementation is needed for a valid inheritance of URLProtocol.
Expand Down

0 comments on commit 9d4d60c

Please sign in to comment.