Last active
October 16, 2020 18:47
-
-
Save florentmorin/04470d557e1cf29ef9a6ba47bb7e258c to your computer and use it in GitHub Desktop.
`URLProtocol` sample code
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
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you