且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Alamofire 4 在 Swift 3 中发送带有参数和正文的 JSON 数据的 POST 请求?

更新时间:2023-01-23 19:30:34

你在这里混合了两件事,pagesizesortBy您是否需要将 url 字符串作为查询字符串传递.现在您的主体请求是 JSON 数组,并且您可以仅使用 URLRequest 使用 Alamofire 发布数组.所以试试这样.

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
}