iosios7swiftnsurlprotocol

NSURLProtocol & swift - error in ios7


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!


Solution

  • 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.