[英]Alamofire 4.3 with Swift 3 , POST request does not working with URL Parameters
I am trying to send a post request as follows, My Router as follows 我正在尝试发送如下发帖请求,我的路由器如下
enum ProfieRouter: URLRequestConvertible {
case loginUser(parameters: Parameters)
case resetPassword(parametrs: Parameters)
var method: HTTPMethod {
switch self {
case .loginUser:
return .post
case .resetPassword:
return .post
}
}
var path: String {
switch self {
case .loginUser:
return "app/api.php?request=login"
case .resetPassword:
return "app/api.php?request=forgettenPassword"
}
}
func asURLRequest() throws -> URLRequest {
let BASEURL = "https://www.example.com/"
let url = try BASEURL.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
switch self {
case .loginUser(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
case .resetPassword(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
}
return urlRequest
}
} }
This is how i call it from ViewController, 这就是我从ViewController调用它的方式,
@IBAction func signInButtonClicked(_ sender: Any) {
let parameters: Parameters = [
"email": "xxxxxx",
"password": "xxxxxx"
]
Alamofire.request(ProfieRouter.loginUser(parameters: parameters)).responseJSON{ response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}
But i got following error as follows, 但是我得到以下错误,
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
Please note that, my API response is a valid when i checked with POSTMAN and Advanced REst Client. 请注意,当我通过POSTMAN和Advanced REst Client检查时,我的API响应是有效的。 And i have tried several question regarding following error but non of them work in my case. 我已经尝试了几个有关以下错误的问题,但是在我的情况下它们都不起作用。
Please can someone point out the mistake i have done here. 请有人指出我在这里犯的错误。 Thank you. 谢谢。
Try this.. 尝试这个..
Modify you web-service calling code like this : 像这样修改您的网络服务调用代码:
// Add default headers if needed.(As per your web-service requirement)
let headers: HTTPHeaders = [
"Accept": "text/html",
"Content-Type" : "application/x-www-form-urlencoded"
]
Alamofire.request("Your URL", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).validate().responseJSON { (response) in
debugPrint(response)
}
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.