Convert URLRequest to NSMutableURLRequest

I am trying to convert URLRequest to NSMutableURLRequest in Swift 3.0, but I cannot get it to work. This is the code I have:

 var request = self.request URLProtocol.setProperty(true, forKey: "", in: request) 

But he says

cannot convert URLRequest type to NSMutableURLRequest type.

When I try to use the “how”, it simply says that the cast will always fail. What should I do?

+5
source share
3 answers

The basics of this: get the modified copy, update the modified copy, and then update the 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 

Better to use to avoid forced reversal.

 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 .

+6
source

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) } 
+1
source

Since the iOS 10 SDK MutableURLRequest deprecated in favor of using the URLRequest structure type with the var keyword. URLRequest also tied to NSMutableURLRequest so you can safely force 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)!) 
0
source

Source: https://habr.com/ru/post/1261404/


All Articles