Reputation: 788
I want to send UTF8 encoded JSON body to my REST API. My code right now is
var body : [String:Any]? = ["version":Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""];
.
.
body?["type"] = type
var url : String = UserDefaults.standard.value(forKey:"url") as! String
url.append("MobileLogin")
Alamofire.request(url, method: .post, parameters:body, encoding: JSONEncoding.default, headers: nil).responseJSON { (responseData) in
if((responseData.result.value) != nil) {
.
.
}
}
The problem is that the JSON sent in not UTF8 encoded. Any idea of how to set something like "JSONEncoding.encode("UTF8")" in the Alamofire request?
Upvotes: 2
Views: 3769
Reputation: 832
try this
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters!, options: options)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
or other way
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
}
}
Alamofire.request(url, method: .post, parameters: [:], encoding: "myBody", headers: [:])
Upvotes: 5