Skip to content

Instantly share code, notes, and snippets.

@TheiOSDude
Created April 11, 2021 20:26
Show Gist options
  • Save TheiOSDude/d29b0c9fda9418ac97bcca61d34330c9 to your computer and use it in GitHub Desktop.
Save TheiOSDude/d29b0c9fda9418ac97bcca61d34330c9 to your computer and use it in GitHub Desktop.
MockURLProtocol.swift
//
// 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