ios - 用于为所有 URLRequest 添加自定义 header 字段的 URLRequest 和 URLSession 的拦截器?

标签 ios iphone swift

我如何为应用程序中的所有 URLRequest 在 URLRequest 和 URLSession 中添加自定义拦截器。所以我可以在一个地方为所有 http 请求添加我自己的自定义 HTTPHeader 字段,有 alamofire 拦截器但我不想使用 alamofire,我想要 urlsession 中的拦截器和 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

最佳答案

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

关于ios - 用于为所有 URLRequest 添加自定义 header 字段的 URLRequest 和 URLSession 的拦截器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53221201/

相关文章:

iphone - 检索应用内购买中的购买信息

ios - Swift PickerViews 问题

ios - 用于下载每天更新一次的网页的 URLSessions 或 AlamoFire?

ios - 来自 Firebase 的数据未排序

ios - 带有来自 URL 的 UIImage 的 SKSpriteNode

iOS - AudioKit 在接听电话时崩溃

ios - 如何使用枚举列表填充 UITableView?

iphone - Objective-C : Last object when using Fast Enumeration?

iphone - 我想在加载新图像时删除 tableviewcell 中的图像。在 iOS 中

ios - 为什么 FBSDKAccessToken.currentAccessToken() 在我的设备上返回 nil,但在 iOS 模拟器中工作正常?