Is there a way to use NSURLProtocol in a NSURLSession with custom config?
Asked Answered
T

1

6

I have a NSURLSession that runs in a background queue. I'm adding my NSURLProtocol subclass to the NSURLsessionConfiguration.protocolClases but the override class func canInitWithRequest(request: NSURLRequest) -> Bool never gets called.

This is how I'm adding my NSURLProtocol

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses!.append(MockNetwork)
urlSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue)

Also I tried with the session not running on background doing but also didn't work:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses!.append(MockNetwork)
urlSession = NSURLSession(configuration: configuration)

As this was not working I just tried:

urlSession = NSURLSession.sharedSession()

And calling this in my AppDelegate

NSURLProtocol.registerClass(MockNetwork)

This does work, what am I doing wrong?!

Tape answered 24/2, 2015 at 20:21 Comment(2)
This does work, what am I doing wrong? Answer: Nothing :)Shrewmouse
but I can't make it work when using a custom config in a background queue... this is driving me CRAZYTape
T
10

After spending some more hours trying to find out why this wasn't working I found the way of doing it.

Instead of:

configuration.protocolClasses?.append(MockNetwork.self)

Do:

var protocolClasses = [AnyClass]()
protocolClasses.append(MockNetwork.self)

let configuration = URLSessionConfiguration.default
configuration.protocolClasses = protocolClasses

After that change everything worked and not necessary to URLProtocol.registerClass(MockNetwork.self)

Tape answered 25/2, 2015 at 13:25 Comment(2)
You would still have to register your custom protocol through NSURLProtocol.registerClass(MockNetwork) in case you were trying to intercept web view requests.Potsherd
protocolClasses uses AnyClass not AnyObject. Your array would need to be [AnyClass]() instead.Guenzi

© 2022 - 2024 — McMap. All rights reserved.