嗨,我是swift的新手,我跟随api调用o发送数据,但它没有发送,我得到了以下回复。
firstName=gggg&lastName=ggg&username=fgg&password=ghh&email=ggg@gg.com&latitude=25.0710693470323&longitude=55.143004052641
responseString {"status":"error","message":"Oops!!!Something went wrong..."}
但是我可以获得所有其他验证消息,例如“用户名不能为空”。
但我尝试使用Postman它也在头文件方法上给出了与上面相同的错误信息,但后来我想出并发送了Body Method和application / x-www-form-urlencoded的形式,然后我得到了成功的响应,如下所示。 / p>
以下是我的API调用...请有人弄清楚我做错了什么或建议我更好的后api电话。
这是我为“/ homefeed”制作的相同API调用方法,并得到了响应,但我们不需要为此发送任何特定参数。请帮帮我。
func addNewUser()
{
let url = URL(string: "https://xxxxxxxxxx.azurewebsites.net/api/addUser")!
let firstName:String = firstnameTextFeild.text!
let lastName:String = lastNameTxtField.text!
let username:String = usernameTextField.text!
let password:String = passwordTextField.text!
let email:String = emailTextField.text!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "firstName=\(firstName)&lastName=\(lastName)&username=\(username)&password=\(password)&email=\(email)&latitude=\(lat)&longitude=\(long)"
print("Sent Data -",postString)
request.httpBody = postString.data(using: .utf8)
/*
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
*/
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
// print("responseString = \(String(describing: responseString))")
print("responseString ", responseString ?? "resSt")
}
task.resume()
}
答案 0 :(得分:1)
您应该像这样传递参数:
A
答案 1 :(得分:1)
使用此代码。为您工作。
安装podfile
pod'Alamofire'
在ViewController中导入Alamofire
func addNewUser(){
let url = "your URL"
var param : [String : AnyObject] = [:]
param = ["firstName": firstnameTextFeild.text! as AnyObject,
"lastName": lastNameTxtField.text! as AnyObject,
"username": usernameTextField.text! as AnyObject,
"password": passwordTextField.text! as AnyObject,
"email": emailTextField.text! as AnyObject,
"latitude": "your latitude" as AnyObject,
"longitude": "your longitude" as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
print(response)
if (response.result.value != nil) {
//your code
}
else{
//your code
}
}
}