有没有办法在带有自定义配置的

有没有办法在带有自定义配置的

本文介绍了有没有办法在带有自定义配置的 NSURLSession 中使用 NSURLProtocol?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在后台队列中运行的 NSURLSession.我将我的 NSURLProtocol 子类添加到 NSURLsessionConfiguration.protocolClases覆盖类 func canInitWithRequest(request: NSURLRequest) ->Bool 永远不会被调用.

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.

这就是我添加我的 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()

并在我的 AppDelegate 中调用它

And calling this in my AppDelegate

NSURLProtocol.registerClass(MockNetwork)

这确实有效,我做错了什么?!

This does work, what am I doing wrong?!

推荐答案

在花了更多时间试图找出为什么这不起作用之后,我找到了解决方案.

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

代替:

configuration.protocolClasses?.append(MockNetwork.self)

做:

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

let configuration = URLSessionConfiguration.default
configuration.protocolClasses = protocolClasses

更改之后一切正常,不需要URLProtocol.registerClass(MockNetwork.self)

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

这篇关于有没有办法在带有自定义配置的 NSURLSession 中使用 NSURLProtocol?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 05:09