【问题标题】:Alamofire, HTTPheaders for post request [string:any]Alamofire,用于发布请求的 HTTPheaders [string:any]
【发布时间】:2021-10-11 00:08:47
【问题描述】:

我需要使用 alamofire 向我的服务器发送一个发布请求,要发送的标头之一不是字符串值,而是一个 Int

阅读 Alamofire 的文档看起来 HTTPHeaders 只是类型 [String: String]

有没有办法将 HTTPHeaders 自定义为 [String:Any]?

我在网上找不到太多可以理解的东西。

谢谢

【问题讨论】:

  • 您是否尝试在字符串中发送标头 Int ?

标签: swift post http-headers alamofire


【解决方案1】:

Alamofire 没有这样的方法,但你可以轻松做到

["hey": 1].mapValues { String(describing: $0) } 返回[String: String]

如果你有很多地方使用它,你可以:

  1. Dictionary 创建扩展
extension Dictionary where Key == String, Value == Any {
    func toHTTPHeaders() -> HTTPHeaders {
        HTTPHeaders(mapValues { String(describing: $0) })
    }
}
// Usage
AF.request(URL(fileURLWithPath: ""), headers: ["": 1].toHTTPHeaders())
  1. HTTPHeaders 创建扩展名
extension HTTPHeaders: ExpressibleByDictionaryLiteral {
    public init(dictionaryLiteral elements: (String, Any)...) {
        self.init()

        elements.forEach { update(name: $0.0, value: String(describing: $0.1)) }
    }
}
// usage
AF.request(URL(fileURLWithPath: ""), headers: HTTPHeaders(["": 1]))
  1. Session 创建扩展名
extension Session {
    open func request(_ convertible: URLConvertible,
                      method: HTTPMethod = .get,
                      parameters: Parameters? = nil,
                      encoding: ParameterEncoding = URLEncoding.default,
                      headers: [String: Any],
                      interceptor: RequestInterceptor? = nil,
                      requestModifier: RequestModifier? = nil) -> DataRequest {

        return request(convertible, method: method, parameters: parameters, encoding: encoding, headers: headers.mapValues { String(describing: $0) }, interceptor: interceptor, requestModifier: requestModifier)
    }
}

// Usage
AF.request(URL(fileURLWithPath: ""), headers: ["": 1])

Alamofire 中没有此类选项的原因是类型安全。当您使用Any 时,您可以在那里传递任何值,因此出错的可能性要高得多。通过要求字符串库确保您自己转换所有需要的值。

我会选择第一个变体,因为当您阅读代码时会更清楚地知道那里发生了一些事情

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 2017-05-11
    • 2017-10-31
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多