Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert URLRequest to NSMutableURLRequest

Tags:

ios

swift

swift3

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?

like image 835
Minimi Avatar asked Dec 16 '16 17:12

Minimi


2 Answers

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.

like image 114
Jeffery Thomas Avatar answered Oct 28 '22 17:10

Jeffery Thomas


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)!)
like image 22
mixel Avatar answered Oct 28 '22 19:10

mixel