Swift Moya sending parameters as JSON in request body

alexxjk picture alexxjk · May 12, 2016 · Viewed 7.6k times · Source

This is how my Endpoint looks:

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
        }
    }
}

Now I want to make my CreateHistoricalEvent method to post its parameters as JSON in request body. What am I missing?

Answer

javimuu picture javimuu · Feb 20, 2017

In Swift3

Change:

    var parameterEncoding: Moya.ParameterEncoding {
        switch self {
        case .CreateHistoricalEvent:
            return ParameterEncoding.Json
        default:
            return ParameterEncoding.URL
        }
    }

To:

   var parameterEncoding: Moya.ParameterEncoding {
        return JSONEncoding.default
    }

If you want to send data with JsonArray, try it:

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
    }

}

and

    var parameterEncoding: Moya.ParameterEncoding {
        switch self {
        case .CreateHistoricalEvent:
            return JsonArrayEncoding.default
        default:
            return JSONEncoding.default
        }
    }