0

I tried to implement a NSURLProtocol as explained in the following tutorial: http://www.raywenderlich.com/76735/using-nsurlprotocol-swift

Everything works fine with iOS8 but in iOS7 I get a runtime error in 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)
}

Error: WebCore: CFNetwork Loader(10): EXC_BREAKPOINT

Does anyone have successfully implemented a NSURLProtocol? Thank you!

Reinhold
  • 234
  • 2
  • 10

2 Answers2

1

It seems like in latest version of XCode (6.0.1), it is not possible to cast NSURLRequest to NSMutableURLRequest

Here is the swift compiler error message:

'NSURLRequest' is not convertible to 'NSMutableURLRequest'

You can create an instance of NSMutableURLRequest in this alternative way

var newRequest = NSMutableURLRequest(URL: self.request.URL, 
               cachePolicy: self.request.cachePolicy, 
               timeoutInterval: self.request.timeoutInterval)
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • Thanks, Anthony! Just in order to improve myself, how did you see the swift compiler error message? The only hint I see is the CFNetwork Loader error. – Reinhold Oct 06 '14 at 13:23
  • I just have a hunch that it is type conversion issue. I wrote a simple type cast in playground and swift emitted the said error message. So you won't see this particular error message in your project – Anthony Kong Oct 06 '14 at 22:46
  • Anthony, I had troubles with your solution on some pages which require a login. Creating a mutable copy as Matt suggested works. – Reinhold Oct 08 '14 at 08:27
0

Your problem is that a copy of a (non-mutable) NSURLRequest is another, non-mutable NSURLRequest, which therefore can't be cast to an NSMutableURLRequest. Try:

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

This should give you a mutable copy of the original request, which should cast just fine.

Matt Gibson
  • 37,886
  • 9
  • 99
  • 128