Created
December 19, 2024 02:20
-
-
Save laprasdrum/0ab74d6b8064005d52ff1244127f3d2f to your computer and use it in GitHub Desktop.
URLProtocolStub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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