Skip to content

Instantly share code, notes, and snippets.

@florentmorin
Last active October 16, 2020 18:47
Show Gist options
  • Save florentmorin/04470d557e1cf29ef9a6ba47bb7e258c to your computer and use it in GitHub Desktop.
Save florentmorin/04470d557e1cf29ef9a6ba47bb7e258c to your computer and use it in GitHub Desktop.
`URLProtocol` sample code
struct User: Encodable {
let firstName: String
let lastName: String
let admin: Bool
}
final class UserProtocol: URLProtocol {
override class func canInit(with request: URLRequest) -> Bool {
return true // Customize here
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request // Customize here
}
override func startLoading() {
guard let client = client else { return }
let headerFields: [String: String] = [
"Content-Type": "application/json"
]
if let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "1.1", headerFields: headerFields) {
client.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
}
let user = User(firstName: "John", lastName: "Doe", admin: true)
guard let data = try? JSONEncoder().encode(user) else { return }
client.urlProtocol(self, didLoad: data)
client.urlProtocolDidFinishLoading(self)
}
override func stopLoading() { }
}
// Configure your URL session here
let urlconfig = URLSessionConfiguration.default
urlconfig.protocolClasses = [UserProtocol.self]
let session = URLSession(configuration: urlconfig)
@editorscut
Copy link

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment