Created
July 18, 2019 08:05
-
-
Save quangDecember/e5f154bed82415e9a115d3da9e060b70 to your computer and use it in GitHub Desktop.
Mock URLProtocol that help mock server response
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 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