Last active
June 30, 2018 19:10
-
-
Save acerosalazar/71344ffede689d88e85ccfca4e3db9b2 to your computer and use it in GitHub Desktop.
CustomURLProtocol for intercepting the HTTP and HTTPS requests made by a macOS/iOS application.
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
import Foundation | |
/*: | |
# Description | |
Can be used to intercept HTTP and HTTPS calls made | |
by the application and introduce custom logic: e.g: | |
logging, custom caching, etc. | |
# Usage | |
## Approach 1: | |
Works when using URLSession.shared. If using in | |
combination with WebKit, it only works with | |
legacy `WebView` objects. | |
``` | |
URLProtocol.registerClass(CustomURLProtocol.self) | |
let session = URLSession.shared | |
``` | |
## Approach 2: | |
Works when using custom URLSession objects. | |
``` | |
let config = URLSessionConfiguration.default | |
config.protocolClasses = [CustomURLProtocol.self] | |
let session = URLSession(configuration: config) | |
``` | |
*/ | |
final class CustomURLProtocol: URLProtocol { | |
override class func canInit(with request: URLRequest) -> Bool { | |
// Required override. Return true in case you need to intercept the request. | |
return false | |
} | |
override class func canonicalRequest(for request: URLRequest) -> URLRequest { | |
// Required override. Nothing to do. | |
return request | |
} | |
override func startLoading() { | |
// Required override. Intercept the call and add custom logic. Then: | |
/* | |
if the call is successful: | |
``` | |
let httpResponse = HTTPURLResonse(...) | |
let data = ... // Response data | |
client?.urlProtocol(self, didReceive: httpResponse, cacheStoragePolicy: .notAllowed) | |
client?.urlProtocol(self, didLoad: data) | |
client?.urlProtocolDidFinishLoading(self) | |
``` | |
*/ | |
/* if the call is not successful: | |
``` | |
let error = NSError(...) | |
client?.urlProtocol(self, didFailWithError: error) | |
``` | |
*/ | |
} | |
override func stopLoading() { | |
// Required Override. Nothing to do. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment