Convert URLRequest to NSMutableURLRequest

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)!)

Tags:

Ios

Swift

Swift3