import Foundation enum MockResponseType: String { case loginSuccess = "login_success" case loginWrongCredentials = "login_wrong_credentials" case } class MockURLProtocol: URLProtocol { static var responseType: MockResponseType? 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 respType = MockURLProtocol.responseType else { return } guard let jsonUrl = Bundle(for: type(of: self)).url(forResource: respType.rawValue, withExtension: "json") else { return } guard let response = HTTPURLResponse(url: jsonUrl, statusCode: 200, httpVersion: "HTTP/2", headerFields: [:]) else { return } let data = try? Data(contentsOf: jsonUrl) client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) if let data = data { client?.urlProtocol(self, didLoad: data) } client?.urlProtocolDidFinishLoading(self) //client?.urlProtocol(self, didFailWithError: error) } override func stopLoading() { // This is called if the request gets canceled or completed. print("") } }