Advertisement
Guest User

swift nsurlprotocol

a guest
Jun 29th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.13 KB | None | 0 0
  1. You can do that using NSURLProtocol, here's a quick example:
  2. Subclass NSURLProtocol class Interceptor: NSURLProtocol { override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest { return request } override class func canInitWithRequest(request: NSURLRequest) -> Bool { // returns true for the requests we want to intercept (*.png) return request.URL.pathExtension == "png" } override func startLoading() { // a request for a png file starts loading // custom response let response = NSURLResponse(URL: request.URL, MIMEType: "image/png", expectedContentLength: -1, textEncodingName: nil) if let client = self.client { client.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed) // reply with data from a local file client.URLProtocol(self, didLoadData: NSData(contentsOfFile: "local file path")!) client.URLProtocolDidFinishLoading(self) } } override func stopLoading() { } }
  3. Somewhere in your code, register the Interceptor class:
  4. NSURLProtocol.registerClass(Interceptor)
  5. There's also a nice article on NSHipster if you want to read more about NSURLProtocol.
  6. Thanks a lot - works like a charm! :)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement