Skip to content

Instantly share code, notes, and snippets.

@laprasdrum
Created December 19, 2024 02:20
Show Gist options
  • Save laprasdrum/0ab74d6b8064005d52ff1244127f3d2f to your computer and use it in GitHub Desktop.
Save laprasdrum/0ab74d6b8064005d52ff1244127f3d2f to your computer and use it in GitHub Desktop.
URLProtocolStub
class URLProtocolStub: URLProtocol {
private struct Stub {
let data: Data?
let response: URLResponse?
let error: Error?
}
private static var stub: Stub?
private static var requestObserver: ((URLRequest) -> Void)?
static func stub(data: Data?, response: URLResponse?, error: Error?) {
Self.stub = Stub(data: data, response: response, error: error)
}
static func startInterceptingRequests() {
URLProtocol.registerClass(URLProtocolStub.self)
}
static func stopInterceptingRequests() {
URLProtocol.unregisterClass(URLProtocolStub.self)
stub = nil
requestObserver = nil
}
static func observeRequests(observer: @escaping (URLRequest) -> Void) {
requestObserver = observer
}
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
if let requestObserver = URLProtocolStub.requestObserver {
client?.urlProtocolDidFinishLoading(self)
return requestObserver(request)
}
if let data = Self.stub?.data {
client?.urlProtocol(self, didLoad: data)
}
if let response = Self.stub?.response {
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
}
if let error = Self.stub?.error {
client?.urlProtocol(self, didFailWithError: error)
}
client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment