【问题标题】:send JSON array as parameter using alamofire in swift在 swift 中使用 alamofire 发送 JSON 数组作为参数
【发布时间】:2017-07-20 17:46:47
【问题描述】:

我正在尝试使用 Alamofire 将此数据(JSON 格式)作为参数发送到 swift 3:

[ {"type":"confirm",
"refKey":"123456789",
"quantity": "1"} ]

但我无法将其转换为参数数据,因为接受的数据类型是[String:Any]

如何传递需要的参数?

【问题讨论】:

    标签: arrays swift swift3 alamofire


    【解决方案1】:

    我在这篇文章中找到了答案: Send an array as a parameter in a Alamofire POST request

    使用Alamofire的JSONSerialization和URLRequest在HTTPBody中发送数据。

        //creates the request        
    
    var request = URLRequest(url: try! "https://api.website.com/request".asURL())
    
    //some header examples
    
    request.httpMethod = "POST"
    request.setValue("Bearer ACCESS_TOKEN_HERE", 
                     forHTTPHeaderField: "Authorization")
    
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    
    //parameter array
    
    let values = ["value1", "value2", "value3"]
    
    request.httpBody = try! JSONSerialization.data(withJSONObject: values)
    
    //now just use the request with Alamofire
    
    Alamofire.request(request).responseJSON { response in
    
        switch (response.result) {
        case .success:
    
            //success code here
    
        case .failure(let error):
    
            //failure code here
        }
    }
    

    作者:莫罗里戈

    【讨论】:

    • 感谢您的提及! =)