Alamofire使用数据设置请求正文

时间:2018-12-24 13:01:32

标签: swift networking alamofire

在objC中,我这样做:

NSData *postData = ...
NSMutableURLRequest *request = ...
[request setHTTPBody:postData];

如何在Swift Alamofire中进行操作?

Alamofire.request(url, method: .post, parameters: nil, encoding: URLEncoding.default, headers: headers)
    request.validate().responseJSON {
...
}

2 个答案:

答案 0 :(得分:2)

Alamfire接受[String:Any]

 do {
     let params  = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
     Alamofire.request(url, method: .post, parameters:params, encoding: JSONEncoding.default, headers: headers)
    request.validate().responseJSON {
     ...
    }
  } 
  catch {
      print(error)
  }

Swift 4.2

Alamofire.request(url, method: .post, parameters: [:], encoding: "test", headers: [:])  

extension String: ParameterEncoding {

    public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        var request = try urlRequest.asURLRequest()
        request.httpBody = data(using: .utf8, allowLossyConversion: false)
        return request
    }

}

答案 1 :(得分:0)

使用Alamofire和Swifty Json库进行适当的api调用和json解析

迅捷的杰森 https://github.com/SwiftyJSON/SwiftyJSON

Alamofire https://github.com/Alamofire/Alamofire

首先以[String:Any]类型创建参数列表

func CallAPI(){

    let parameters: [String: Any] = [
    "Username": "Admin",
    "Password": "123456",
    "Language_Code": "EN"]


    Alamofire.request("Your API Url", method: .post, parameters: parameters, encoding: JSONEncoding.default)
    .responseJSON { response in

    if((response.result.value) != nil) {

    let ResultJson = JSON(response.result.value!)

    print("ResultJson==",ResultJson)
    }
 }
}