Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

ios - How to send POST request with both parameter and body for JSON data in Swift 3 using Alamofire 4?

Postman api url added below. enter image description here

Present code :

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

I don't know how to add body request through this code. Please help me to slove this problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are mixing two things here, page,size and sortBy is you need to pass with the url string as query string. Now your body is request is JSON Array and you can post array with Alamofire only using URLRequest. So try like this.

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...