9

我正在使用moya 库发出 POST 请求。在 TargetType 中,我看不到任何属性来传递参数 [JSON 正文] 以及 POST 请求。在这里,我附上 TargetType

public protocol TargetType {

    /// The target's base `URL`.
    var baseURL: URL { get }

    /// The path to be appended to `baseURL` to form the full `URL`.
    var path: String { get }

    /// The HTTP method used in the request.
    var method: Moya.Method { get }

    /// Provides stub data for use in testing.
    var sampleData: Data { get }

    /// The type of HTTP task to be performed.
    var task: Task { get }

    /// Whether or not to perform Alamofire validation. Defaults to `false`.
    var validate: Bool { get }

    /// The headers to be used in the request.
    var headers: [String: String]? { get }
}

public extension TargetType {
    var validate: Bool {
        return false
    }
}
4

1 回答 1

22

最后,我得到了解决问题的方法。在 Moya 10.0 中,我们可以在任务属性 [TargetType] 中传递 http 正文 JSON 有效负载。

点击这里参考

var task: Task {
    switch self {
    case .zen, .showUser, .showAccounts: // Send no parameters
        return .requestPlain
    case let .updateUser(_, firstName, lastName):  // Always sends parameters in URL, regardless of which HTTP method is used
        return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: URLEncoding.queryString)
    case let .createUser(firstName, lastName): // Always send parameters as JSON in request body
        return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: JSONEncoding.default)
    }
}
于 2018-01-22T10:18:25.207 回答