将URLRequest转换为NSMutableURLRequest

时间:2016-12-16 17:58:11

标签: ios swift swift3

我试图在Swift 3.0中将URLRequest转换为NSMutableURLRequest,但我无法让它发挥作用。这是我的代码:

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

但它说

  

无法将类型URLRequest转换为类型NSMutableURLRequest。

当我尝试使用'作为'它只是说演员将永远失败。我该怎么办?

4 个答案:

答案 0 :(得分:7)

这方面的基础是获取可变副本,更新可变副本,然后使用可变副本更新请求。

let mutableRequest = ((self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!
URLProtocol.setProperty(true, forKey: "", in: mutableRequest)
self.request = mutableRequest as URLRequest

最好使用避免强制解包。

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

注意:self.request必须声明var而不是let

答案 1 :(得分:1)

由于不推荐使用iOS 10 SDK MutableURLRequest,而赞成使用带有URLRequest关键字的var结构类型。同样URLRequest is bridgedNSMutableURLRequest,这样您就可以安全地进行强制演员投放:

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

答案 2 :(得分:1)

使用Swift 4.1,以下解决方案对我有效

if let mutableRequest = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest {
    mutableRequest.addValue("VALUE", forHTTPHeaderField: "KEY")
    print(mutableRequest)
}

答案 3 :(得分:0)

迅速工作5

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