Minimi
Minimi

Reputation: 961

Convert URLRequest to NSMutableURLRequest

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?

Upvotes: 14

Views: 10426

Answers (4)

Zgpeace
Zgpeace

Reputation: 4467

work in swift 5

guard let mutableRequest = (self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else {
            // Handle the error
            return
        }
URLProtocol.setProperty(true, forKey: "protocolKey", in: mutableRequest)

Upvotes: 0

ossamacpp
ossamacpp

Reputation: 686

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

Upvotes: 2

mixel
mixel

Reputation: 25836

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

Upvotes: 4

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

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.

Upvotes: 15

Related Questions