这就是我的Endpoint的样子:
extension MyEndpoint: TargetType {
var baseURL: NSURL { return NSURL(string: "http://10.0.1.13:5000")! }
var path: String {
switch self {
case .SearchForNodes(_, _, _):
return "/api/search/node/"
case .CreateHistoricalEvent(_):
return "/api/node/historicalevent/"
}
}
var method: Moya.Method {
switch self {
case .SearchForNodes(_, _, _):
return .GET
case .CreateHistoricalEvent(_):
return .POST
}
}
var parameters: [String: AnyObject]? {
switch self {
case .SearchForNodes(let startsWith, let page, let pageSize):
return ["startsWith": startsWith, "page": page, "pageSize": pageSize]
case .CreateHistoricalEvent(let title):
return ["Title": title]
}
}
var parameterEncoding: Moya.ParameterEncoding {
switch self {
case .CreateHistoricalEvent:
return ParameterEncoding.Json
default:
return ParameterEncoding.URL
}
}
}
现在我想让我的CreateHistoricalEvent方法在请求体中将其参数作为JSON发布。我错过了什么?
答案 0 :(得分:3)
在Swift3中
更改强>:
var parameterEncoding: Moya.ParameterEncoding {
switch self {
case .CreateHistoricalEvent:
return ParameterEncoding.Json
default:
return ParameterEncoding.URL
}
}
要强>:
var parameterEncoding: Moya.ParameterEncoding {
return JSONEncoding.default
}
如果您想使用JsonArray发送数据,请尝试:
import Alamofire
struct JsonArrayEncoding: Moya.ParameterEncoding {
public static var `default`: JsonArrayEncoding { return JsonArrayEncoding() }
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var req = try urlRequest.asURLRequest()
let json = try JSONSerialization.data(withJSONObject: parameters!["jsonArray"]!, options: JSONSerialization.WritingOptions.prettyPrinted)
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.httpBody = json
return req
}
}
和
var parameterEncoding: Moya.ParameterEncoding {
switch self {
case .CreateHistoricalEvent:
return JsonArrayEncoding.default
default:
return JSONEncoding.default
}
}
答案 1 :(得分:0)
extension MoyaProvider {
public class func JSONEndpointMapping(target: Target) -> Endpoint<Target> {
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(
URL: url,
sampleResponseClosure: {
.NetworkResponse(200, target.sampleData)
},
method: target.method,
parameters: target.parameters,
parameterEncoding: Moya.ParameterEncoding.JSON
)
}
}
let DemoAPI = MoyaProvider<DemoTarger>(endpointClosure: MoyaProvider.JSONEndpointMapping)