URLRequest和URLSession的拦截器,用于为所有URLRequest添加自定义标头字段?

时间:2018-11-09 07:05:15

标签: ios iphone swift

如何为应用程序中的所有URLRequest在URLRequest和URLSession中添加自定义拦截器。所以我可以在一个地方为所有HTTP请求添加自己的自定义HTTPHeader字段,这里有alamofire Interceptor,但我不想使用alamofire,我想在urlsession中使用Interceptor,在Swift 4中使用urlrequest。 我扩展了urlrequest,但对我不起作用。

//1st One    
extension URLRequest {
            init(_ url: URL) {
                self.init(url: url)
                self.setValue(deviceInformation.shared.deviceModel, forHTTPHeaderField: "deviceModel")
                self.allHTTPHeaderFields?.updateValue(deviceInformation.shared.deviceModel, forKey: "deviceModel1")
            }
        }

// 2nd one

extension URLRequest {
   var instance: URLRequest {
     var instanceRequest: URLRequest!
      instanceRequest.allHTTPHeaderFields?.updateValue(deviceInformation.shared.deviceModel, forKey: "deviceModel")
      instanceRequest.addValue(deviceInformation.shared.deviceSystemName, forHTTPHeaderField: "deviceSystemName")
      instanceRequest.addValue(deviceInformation.shared.deviceSystemVersion, forHTTPHeaderField: "deviceSystemVersion")
      instanceRequest.addValue(deviceInformation.shared.getAppVersion(), forHTTPHeaderField: "appVersion")
       return instanceRequest
    }
}
//both are not working

1 个答案:

答案 0 :(得分:2)

 //Here is the answer for "Custom Header Fields" for all URLRequest.   

extension URLRequest {
        init(_ url: URL) {
            self.init(url: url)
            self.setValue("Value", forHTTPHeaderField: "fieldNamme")
        }
    }

//how to use
func aBC(){
    //how to call it.
    let myUrl = URL(string: "Your url string")
    let request =  URLRequest(myUrl) //this will work and add custom header
    //let request =  URLRequest(url: myUrl) // this will not work because it call the super init method of urlrequest.

    request.httpMethod = "POST"
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: ["bodyParam" : "value"], options: [])
    } catch let error {
        return
    }

    let dataTask = URLSession.shared.dataTask(with: request) {
        data,response,error in

        do {
            //.
           // .
           // .
        } catch let error as NSError {
        }
    }
    dataTask.resume()
}