Skip to content

Instantly share code, notes, and snippets.

@pushkarnk
Created September 8, 2017 08:57
Show Gist options
  • Save pushkarnk/2689ac581c8e3775312b2ef26805864b to your computer and use it in GitHub Desktop.
Save pushkarnk/2689ac581c8e3775312b2ef26805864b to your computer and use it in GitHub Desktop.
import Foundation
import Dispatch
class ProxyURLProtocol: URLProtocol {
static var session: URLSession!
struct PropertyKeys {
static let handledByForwarderURLProtocol = "HandledByProxyURLProtocol"
}
var activeTask: URLSessionTask?
override class func canInit(with request: URLRequest) -> Bool {
return true
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
let urlRequest = URLRequest(url: URL(string: "http://httpbin.org/get")!)
//session = Foundation.URLSession(configuration: .default, delegate: self, delegateQueue: nil)
activeTask = ProxyURLProtocol.session.dataTask(with: urlRequest)
activeTask?.resume()
}
override func stopLoading() {
activeTask?.cancel()
}
}
extension ProxyURLProtocol: URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
client?.urlProtocol(self, didLoad: data)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let response = task.response {
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
}
client?.urlProtocolDidFinishLoading(self)
}
}
let urlRequest = URLRequest(url: URL(string: "http://google.com")!)
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [ProxyURLProtocol.self]
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
ProxyURLProtocol.session = session
let task = session.dataTask(with: urlRequest)
task.resume()
dispatchMain()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment