Swift Moya 在请求正文中将参数作为 JSON 发送
Posted
技术标签:
【中文标题】Swift Moya 在请求正文中将参数作为 JSON 发送【英文标题】:Swift Moya sending parameters as JSON in request body 【发布时间】:2016-05-12 18:55:44 【问题描述】:这就是我的 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 发布到请求正文中。我错过了什么?
【问题讨论】:
【参考方案1】:在 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
【讨论】:
【参考方案2】: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)
【讨论】:
以上是关于Swift Moya 在请求正文中将参数作为 JSON 发送的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Swift 3 中使用 Alamofire 在 POST 请求中将给定的 JSON 作为参数发送?