web-dev-qa-db-ja.com

POST Swift 3でAlamofire 4を使用してJSONデータのパラメーターと本文の両方を含むリクエストを送信しますか?

以下にPostman API URLを追加しました。 enter image description here

現在のコード:

let baseUrl = "abc.com/search/"
let param  =  [
        "page":"1",
        "size":"5",
        "sortBy":"profile_locality"
    ]

    let headers = [
        "Content-Type": "application/json"
    ]


    Alamofire.SessionManager.default.request("\(baseUrl)field", method: .post,parameters: param, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
        print(response.request ?? "no request")  // original URL request
        if(response.response?.statusCode != nil){
            print("done")
            if self.checkResponse(response.response!.statusCode){
                let json = JSON(data: response.data!)
                //print("at_LeadStop json \(json)")
                return completionHandler(json, false)

            } else {
                return completionHandler(JSON.null, true)
            }
        } else {
            print("gone")
            return completionHandler(JSON.null, true)
        }}

このコードを介してボディリクエストを追加する方法がわかりません。この問題を解決してください。

9
Kushal Shrestha

ここでは、pagesizesortByの2つのことを混在させています。クエリ文字列としてURL文字列を渡す必要があります。これで、あなたのボディはJSON配列になり、Alamofireのみを使用してURLRequestで配列をポストできます。だからこのようにしてみてください。

let baseUrl = "abc.com/search/"
let queryStringParam  =  [
    "page":"1",
    "size":"5",
    "sortBy":"profile_locality"
]
//Make first url from this queryStringParam using URLComponents
var urlComponent = URLComponents(string: baseUrl)!
let queryItems = queryStringParam.map  { URLQueryItem(name: $0.key, value: $0.value) }
urlComponent.queryItems = queryItems

//Now make `URLRequest` and set body and headers with it
let param = [
    [
        "fieldName" : "abc",
        "fieldValue":"xyz"
    ],
    [
        "fieldName" : "123",
        "fieldValue":"789"
    ]
]
let headers = [ "Content-Type": "application/json" ]
var request = URLRequest(url: urlComponent.url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: param)
request.allHTTPHeaderFields = headers

//Now use this URLRequest with Alamofire to make request
Alamofire.request(request).responseJSON { response in
    //Your code
}
18
Nirav D

これを試してください:カスタムエンコーディングを使用して

 struct JSONStringArrayEncoding: ParameterEncoding {
    private let array: [[String : Any]]

    init(array: [[String : Any]]) {
        self.array = array
    }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var urlRequest = try urlRequest.asURLRequest()

        let data = try JSONSerialization.data(withJSONObject: array, options: [])

        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
        }

        urlRequest.httpBody = data

        return urlRequest
    }
}

呼び出し

let values  = [
            [
                "fieldName" : "abc",
                "fieldValue":"xyz"
            ],
            [
                "fieldName" : "123",
                "fieldValue":"789"
            ]
        ]

        let param  =  [
            "page":"1",
            "size":"5",
            "sortBy":"profile_locality"
        ]

        let parameterEncoding = JSONStringArrayEncoding.init(array: values)

        Alamofire.request("url", method: .post, parameters: param, encoding:parameterEncoding  ).validate().response { (responseObject) in
            // do your work
        }
1
KKRocks