我使用的是Alamoire,我想用内容类型“text/html;charset=utf-8”对参数进行编码。我按照文档https://github.com/Alamofire/Alamofire进行了自定义参数编码,并创建了
let custom: (URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) = {
(URLRequest, parameters) in
let mutableURLRequest = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
mutableURLRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
mutableURLRequest.body = // don't know if I need to set this
return (mutableURLRequest, nil)
}
func postData(){
Alamofire.request(.POST, baseUrl, parameters: parameters, encoding: .Custom(custom))
.responseString{ (request, response, data, error) in
println("blah")
}
}
var parameters = [String: AnyObject]()
func setParams(){
parameters = [
"CONTRACT ID" : chosenContract!.iD.toInt()!,
"FEE AMOUNT" : 0,
"TRANSACT DATE" : today
]
}
这里有几个问题。让我们把它们分解为1x1。
编译器问题
编译器的问题是因为返回元组的类型错误。在AlamoFire1.3.0中,我们将返回类型改为一个NSMutableURLRequest
类型,这最终使总体上的操作更加容易。这样可以解决编译器问题。
设置httpbody
现在你有几个选择。
选项1-将数据编码为JSON
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters!, options: options)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
let parameters: [String: AnyObject] = [:] // fill in
let encodableURLRequest = NSURLRequest(URL: URL)
let encodedURLRequest = ParameterEncoding.URL.encode(encodableURLRequest, parameters).0
let mutableURLRequest = NSMutableURLRequest(URL: encodedURLRequest.URLString)
mutableURLRequest.HTTPMethod = "OST"
mutableURLRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
Alamofire.request(mutableURLRequest)
.response { request, response, data, error in
print(request)
print(response)
print(error)
}
关于swift - Alamofire自定义参数编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31860664/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |