问题
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?
回答1:
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.
回答2:
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)!)
回答3:
Using Swift 4.1, the following solution worked for me
if let mutableRequest = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest {
mutableRequest.addValue("VALUE", forHTTPHeaderField: "KEY")
print(mutableRequest)
}
来源:https://stackoverflow.com/questions/41189959/convert-urlrequest-to-nsmutableurlrequest