Reinhold
Reinhold

Reputation: 234

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!

Upvotes: 0

Views: 630

Answers (2)

Matt Gibson
Matt Gibson

Reputation: 38238

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.

Upvotes: 0

Anthony Kong
Anthony Kong

Reputation: 40664

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)

Upvotes: 1

Related Questions