I'm trying to convert a URLRequest
to a NSMutableURLRequest
in Swift 3.0 but I can't get it to work. This is the code I have:
var request = self.request
URLProtocol.setProperty(true, forKey: "", in: request)
But it says
cannot convert type URLRequest to type NSMutableURLRequest.
When I try to cast using 'as' it just says the cast will always fail. What do I do?
The basics of this are get a mutable copy, update the mutable copy then update request with the mutable copy.
let mutableRequest = ((self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!
URLProtocol.setProperty(true, forKey: "", in: mutableRequest)
self.request = mutableRequest as URLRequest
It would be better to use avoid the forced unwrap.
guard let mutableRequest = (self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else {
// Handle the error
return
}
URLProtocol.setProperty(true, forKey: "", in: mutableRequest)
self.request = mutableRequest as URLRequest
Note: self.request
must be declared var
not let
.
Since iOS 10 SDK MutableURLRequest
is deprecated in favor of using URLRequest
struct type with var
keyword. Also URLRequest
is bridged to NSMutableURLRequest
so you can safely make forced casts:
let r = URLRequest(url: URL(string: "https://stackoverflow.com")!) as! NSMutableURLRequest
URLProtocol.setProperty("Hello, world!", forKey: "test", in: r)
print(URLProtocol.property(forKey: "test", in: r as! URLRequest)!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With