【问题标题】:NSURLProtocol & swift - error in ios7NSURLProtocol & swift - ios7 中的错误
【发布时间】:2014-10-03 08:38:33
【问题描述】:

我尝试按照以下教程中的说明实现 NSURLProtocol:http://www.raywenderlich.com/76735/using-nsurlprotocol-swift

在 iOS8 上一切正常,但在 iOS7 中我在 startLoading() 中遇到运行时错误。

override func startLoading() {
    var newRequest = self.request.copy() as NSMutableURLRequest //<- this line fails
    NSURLProtocol.setProperty(true, forKey: "MyURLProtocolHandledKey", inRequest: newRequest)

    self.connection = NSURLConnection(request: newRequest, delegate: self)
}

错误:WebCore:CFNetwork Loader(10):EXC_BREAKPOINT

有人成功实现了 NSURLProtocol 吗?谢谢!

【问题讨论】:

  • 如果使用var newRequest = self.request.mutableCopy() as NSMutableURLRequest,是否有效?因为我不希望 copy() 返回一个可变请求。
  • 谢谢马特,这行得通!
  • 酷;我已将其添加为答案。

标签: ios ios7 swift nsurlprotocol


【解决方案1】:

似乎在最新版本的 XCode (6.0.1) 中,无法将 NSURLRequest 转换为 NSMutableURLRequest

这里是 swift 编译器错误信息:

'NSURLRequest' is not convertible to 'NSMutableURLRequest'

您可以通过这种替代方式创建NSMutableURLRequest 的实例

var newRequest = NSMutableURLRequest(URL: self.request.URL, 
               cachePolicy: self.request.cachePolicy, 
               timeoutInterval: self.request.timeoutInterval)

【讨论】:

  • 谢谢,安东尼!只是为了提高自己,你是怎么看到swift编译器错误信息的?我看到的唯一提示是 CFNetwork Loader 错误。
  • 我只是预感到这是类型转换问题。我在操场上写了一个简单的类型转换,并迅速发出了上述错误消息。所以你不会在你的项目中看到这个特定的错误信息
  • Anthony,我在某些需要登录的页面上遇到了您的解决方案的问题。按照 Matt 的建议创建一个可变副本。
【解决方案2】:

您的问题是(非可变)NSURLRequest 的副本是另一个不可变的 NSURLRequest,因此不能转换为 NSMutableURLRequest。试试:

var newRequest = self.request.mutableCopy() as NSMutableURLRequest // mutableCopy() instead of copy()

这应该会给你一个原始请求的可变副本,应该可以很好地转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2015-07-23
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多