Skip to content

Instantly share code, notes, and snippets.

@quangDecember
Created July 18, 2019 08:05
Show Gist options
  • Save quangDecember/e5f154bed82415e9a115d3da9e060b70 to your computer and use it in GitHub Desktop.
Save quangDecember/e5f154bed82415e9a115d3da9e060b70 to your computer and use it in GitHub Desktop.
Mock URLProtocol that help mock server response
import Foundation
class MockURLProtocol: URLProtocol {
static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data) )?
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func stopLoading() {
}
override func startLoading() {
guard let handler = MockURLProtocol.requestHandler else {
return
}
do {
let (response, data) = try handler(request)
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: data)
client?.urlProtocolDidFinishLoading(self)
} catch {
client?.urlProtocol(self, didFailWithError: error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment