gpt4 book ai didi

ios - 无 url 编码的 Moya Alamofire 请求

转载 作者:行者123 更新时间:2023-11-30 11:35:55 25 4
gpt4 key购买 nike

如何使用 Moya 使用 get-API(具有以下请求结构)?

http://some.environment.com/some/api/some/contacts/81193?types=["详细信息", "权限"]

这是我尝试过的。

enum MyApiTarget: TargetType {

case getInfo(contactID: Int, types: [String])

public var baseURL: URL {
switch self {
case .getInfo:
return URL(string: "http://some.environment.com/some/api")!
}
}

public var path: String {
switch self {
case .getInfo(contactID: let contactId, types: _):
return "/some/contacts/\(contactId)"
}
}

public var method: Moya.Method {
switch self {
case .getInfo:
return .get
}
}

public var sampleData: Data {
return Data()
}

public var task: Task {
switch self {
case .getInfo(contactID: _, types: let types):
return .requestParameters(
parameters: ["types" : types],
encoding: URLEncoding.queryString
)
}
}

public var headers: [String: String]? {
return nil
}

}

以上代码生成以下 URL。

http://some.environment.com/some/api/some/contacts/81193?types%5B%5D=details&types%5B%5D=permissions

我尝试了以下编码

  • URLEncoding.queryString
  • URLEncoding.default
  • URLEncoding.httpBody
  • JSONEncoding.default
  • JSONEncoding.prettyPrinted

没有任何编码可以帮助我产生预期的结果。

最佳答案

我通过如下代码解决了这个问题。

按如下方式替换任务。

public var task: Task {
switch self {
case .getInfo(contactID: _, types: let types):
var arrayOfTypesInString = types.joined(separator: "\", \"")
arrayOfTypesInString = "\"\(arrayOfTypesInString)\""
let params = ["types": "[\(arrayOfTypesInString)]"]
return .requestParameters(
parameters: params,
encoding: URLEncoding.queryString
)
}
}
}

目前,我已经完成了手动 JSON 编码。另一种方法是,首先将数据转换为 JSON 并从 JSON 创建字符串并提供。

关于ios - 无 url 编码的 Moya Alamofire 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49775154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com