我一直在关注本教程:https://devdactic.com/parse-json-with-swift/ 并遵循了每条指令。但我只是不能使http post请求工作,因为看起来我的api服务无法获取所请求的参数。所以这是我的httppost请求方法:
private func makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
request.HTTPBody = jsonBody
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, nil)
} else {
onCompletion(nil, error)
}
})
task.resume()
} catch {
// Create your personal error
onCompletion(nil, nil)
}
}
然后我创建了一个函数来调用它:
func registerNewUser(email: String,url: String, onCompletion: (JSON) -> Void) {
let route = baseURL + url
print(route)
let postItems:[String: String] = ["email": email]
print("postitems",postItems)
makeHTTPPostRequest(route, body: postItems, onCompletion: { json, err in
onCompletion(json as JSON)
print("response",json)
})
}
然后从注册控制器调用它:
func requestSignUp()
{
if((emailField.text?.isEmpty) == false)
{
//performSegueWithIdentifier("showVerification", sender: signUpBtn)
let url = "user/signup"
RestApiManager.sharedInstance.registerNewUser(emailField.text! as String, url: url as String, onCompletion: {
(json: JSON) in if let results = json[0].array {
for entry in results {
print(entry)
}
}
})
}
}
打印显示注册用户下的帖子格式为:
postitems [“email”:“dasdsd”]
我的服务回复显示了这一点:
response {
"responseData" : {
},
"responseStat" : {
"status" : false,
"isLogin" : false,
"requestError" : [
],
"msg" : "The email field is required.",
"extra" : {
}
}
}
电子邮件字段参数为电子邮件,成功提交后会显示如下内容:
{
"responseStat": {
"status": true,
"isLogin": false,
"msg": "Successfully Registered an, your password has been sent to your email",
"requestError": [],
"extra": {}
},
"responseData": ""
}
答案 0 :(得分:3)
在 makeHTTPPostRequest 中添加此行使其正常工作:
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
答案 1 :(得分:0)
您可以在Alamofire旁边使用SwiftyJSON和Ease:
static func requestToSendObject(value: YOUROBJECT) {
let url = NSURL(string: "http://google.com")!
let params: [String: AnyObject] = [
"object_key" : value
]
Alamofire.request(.POST, url, parameters: params, encoding: .JSON, headers: nil).responseJSON {
if let data = response.result.value {
let responseJSON = JSON(data)
// Use the responseJSON
}
}
}