Created
April 11, 2021 20:26
-
-
Save TheiOSDude/d29b0c9fda9418ac97bcca61d34330c9 to your computer and use it in GitHub Desktop.
MockURLProtocol.swift
This file contains 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
// | |
// File.swift | |
// | |
// | |
// Created by Lee Burrows on 04/01/2021. | |
// | |
import Foundation | |
class MockURLProtocol: URLProtocol { | |
static var error: Error? | |
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 startLoading() { | |
if let error = MockURLProtocol.error { | |
client?.urlProtocol(self, didFailWithError: error) | |
return | |
} | |
guard let handler = MockURLProtocol.requestHandler else { | |
assertionFailure("Received unexpected request with no handler set") | |
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) | |
} | |
} | |
override func stopLoading() { | |
// TODO: Andd stop loading here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment