Created
September 19, 2022 13:49
-
-
Save emndeniz/1911b21ef5cb89f67062a067b4c9669d to your computer and use it in GitHub Desktop.
MockURL
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
import Foundation | |
class MockURL: URLProtocol { | |
static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data?))? | |
override class func canInit(with request: URLRequest) -> Bool { | |
// To check if this protocol can handle the given request. | |
return true | |
} | |
override class func canonicalRequest(for request: URLRequest) -> URLRequest { | |
// Here you return the canonical version of the request but most of the time you pass the orignal one. | |
return request | |
} | |
override func startLoading() { | |
guard let handler = MockURLProtocol.requestHandler else { | |
fatalError("Handler is unavailable.") | |
} | |
do { | |
// 2. Call handler with received request and capture the tuple of response and data. | |
let (response, data) = try handler(request) | |
// 3. Send received response to the client. | |
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) | |
if let data = data { | |
// 4. Send received data to the client. | |
client?.urlProtocol(self, didLoad: data) | |
} | |
// 5. Notify request has been finished. | |
client?.urlProtocolDidFinishLoading(self) | |
} catch { | |
// 6. Notify received error. | |
client?.urlProtocol(self, didFailWithError: error) | |
} | |
} | |
override func stopLoading() { | |
// This is called if the request gets canceled or completed. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment