swift – 通过Alamofire发送json数组

前端之家收集整理的这篇文章主要介绍了swift – 通过Alamofire发送json数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否可以在POST请求中直接发送数组(不包含在字典中)。显然参数参数应该得到一个映射:[String:AnyObject]?
但我想能够发送以下示例json:
[
    "06786984572365","06644857247565","06649998782227"
]
你可以用NSJSONSerialization编码JSON,然后自己生成NSURLRequest。例如,在Swift 2:
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json",forHTTPHeaderField: "Content-Type")

let values = ["06786984572365","06649998782227"]

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values,options: [])

Alamofire.request(request)
    .responseJSON { response in
        // do whatever you want here
        switch response.result {
        case .Failure(let error):
            print(error)

            // if web service reports error,sometimes the body of the response
            // includes description of the nature of the problem,e.g.

            if let data = response.data,let responseString = String(data: data,encoding: NSUTF8StringEncoding) {
                print(responseString)
            }
        case .Success(let responSEObject):
            print(responSEObject)
        }
}

或者,在Swift 3:

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json","06649998782227"]

request.httpBody = try! JSONSerialization.data(withJSONObject: values)

Alamofire.request(request)
    .responseJSON { response in
        // do whatever you want here
        switch response.result {
        case .failure(let error):
            print(error)

            if let data = response.data,encoding: .utf8) {
                print(responseString)
            }
        case .success(let responSEObject):
            print(responSEObject)
        }
}
原文链接:https://www.f2er.com/swift/321066.html

猜你在找的Swift相关文章