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

邮差的信 提交于 2019-12-21 12:59:24

问题


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?!


回答1:


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)



来源:https://stackoverflow.com/questions/28705534/is-there-a-way-to-use-nsurlprotocol-in-a-nsurlsession-with-custom-config

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!