Alamofire 将 bool 转换为 int

问题描述 投票:0回答:2

我有请求函数和参数字典。字典包含 [String, Any]。我需要在参数中发送 Bool,但 alamofire 将我的 Bool 转换为 Int,而服务器无法获取它。我如何发送布尔值?

我的功能:

func postDataFor(methodPath: String, params:[String:Any], completion: @escaping (Any)->()) {
    guard let url = URL(string:baseURL+methodPath) else {print("fail url"); return}

        let token_type = KeychainWrapper.standard.string(forKey: "token_type")
        let access_token = KeychainWrapper.standard.string(forKey: "access_token")

        let headers:HTTPHeaders? = ["Authorization": "\(token_type ?? "") \(access_token ?? "")"]


        Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.queryString, headers: headers).response { response in

            if let data = response.data {
                completion(data)
            } else {
           print("error")
        }
    }
}

我尝试发送:

    ▿ 2 elements
  ▿ 0 : 2 elements
    - key : "promoId"
    - value : 6
  ▿ 1 : 2 elements
    - key : "isFavorite"
    - value : true

但这发送alamofire:

?isFavorite=1&promoId=6 
swift alamofire
2个回答
9
投票

我猜所有这些值都存储在

params
中。如果是这样,请将
isFavorite
更改为字符串:

let params = [
    "promoId": 6,
    "isFavorite": String(isFavorite)
]

2
投票

用于将参数编码为:

// Define custom encoding with URLEncoding.BoolEncoding.literal
let encoding = URLEncoding(boolEncoding: .literal)

示例:

import Alamofire

func postDataFor(methodPath: String, params: [String: Any], completion: @escaping (Data?) -> Void) {
    guard let url = URL(string: baseURL + methodPath) else {
        print("Failed to create URL")
        return
    }

    let tokenType = KeychainWrapper.standard.string(forKey: "token_type") ?? ""
    let accessToken = KeychainWrapper.standard.string(forKey: "access_token") ?? ""

    let headers: HTTPHeaders = ["Authorization": "\(tokenType) \(accessToken)"]

    // Define custom encoding with URLEncoding.BoolEncoding.literal
    let encoding = URLEncoding(boolEncoding: .literal)

    Alamofire.request(url, method: .post, parameters: params, encoding: encoding, headers: headers).response { response in
        if let data = response.data {
            completion(data)
        } else {
            print("Error: No data received")
            completion(nil)
        }
    }
}

通过此修改,Bool 值将被编码为 true 或 false 文字,而不是转换为整数。现在,当您调用 postDataFor 时,您的 Bool 参数将被正确编码。

© www.soinside.com 2019 - 2024. All rights reserved.