Skip to content

Instantly share code, notes, and snippets.

@jawwad
Last active February 8, 2016 09:11
Show Gist options
  • Save jawwad/f9cbbe579cdc2e553e86 to your computer and use it in GitHub Desktop.
Save jawwad/f9cbbe579cdc2e553e86 to your computer and use it in GitHub Desktop.
import Foundation
let session = NSURLSession.sharedSession()
let requestIsBeingHandledKey = "RequestIsBeingHandledKey"
class CustomNSURLProtocol: NSURLProtocol {
override class func canInitWithRequest(request: NSURLRequest) -> Bool {
if NSURLProtocol.propertyForKey(requestIsBeingHandledKey, inRequest: request) != nil {
return false // Prevent recursize loop
}
return false // Add condition here
}
override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
override class func requestIsCacheEquivalent(aRequest: NSURLRequest, toRequest bRequest: NSURLRequest) -> Bool {
return super.requestIsCacheEquivalent(aRequest, toRequest:bRequest)
}
override func startLoading() {
let newRequest = request.mutableCopy() as! NSMutableURLRequest
NSURLProtocol.setProperty(true, forKey: requestIsBeingHandledKey, inRequest: newRequest)
session.dataTaskWithRequest(newRequest) { data, response, error in
if let error = error {
self.client!.URLProtocol(self, didFailWithError: error)
} else if let data = data {
self.completeRequestWithData(data)
} else {
fatalError("Data is nil")
}
}.resume()
}
override func stopLoading() { }
private func completeRequestWithData(data: NSData) {
self.client!.URLProtocol(self, didReceiveResponse: NSHTTPURLResponse(URL: request.URL!, statusCode: 200, HTTPVersion: nil, headerFields: nil)!, cacheStoragePolicy: .NotAllowed)
self.client!.URLProtocol(self, didLoadData: data)
self.client!.URLProtocolDidFinishLoading(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment