简体   繁体   中英

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!

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM