我的CURL是
curl --header "secret: mytoken" --data "a=addPost&session=mySession&postBody=test" https://example.com/testing/
我想与Alamofire一起使用。如何将其转换为Swift代码?
更新。
我的代码是:
@IBAction func postTapped(_ sender: UIButton) {
guard let url = URL(string: "https://example.com/testing/") else { return }
let headers = [
"secret": "mytoken"
]
let parameters = [
"a": "addPost",
"session": "mySession",
"postBody": "test"
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
print(response)
}
}
但是我收到此错误:
失败:responseSerializationFailed(原因: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误: 错误域= NSCocoaErrorDomain代码= 3840“周围的无效值 字符0。“ UserInfo = {NSDebugDescription =无效值 字符0。}))
更新2。
当我在Mac OS终端中使用此CURL时,我得到了正确的JSON:
{"result":100,"data":{"id":"mydata"}
但是在swift
代码中我出错了。
答案 0 :(得分:1)
let parameters: Parameters = [
"a": "addPost",
"session": "mySession",
"postBody": "test"
]
let headers: HTTPHeaders = [
"secret": "mytoken"
]
Alamofire.request("https://example.com/testing/", parameters: parameters, headers: headers).responseJSON { response in
// do something
}
答案 1 :(得分:1)
解决方案-使用URLEncoding(目标:.httpBody)(thx Larme):
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).responseJSON { (response) in
print(response)
}