1)
我是使用alamofire的新手。这是我尝试使用alamofire进行网络服务检查我错了。我已经在loginviewcontroller.swift
中创建了一个登录网络服务,如下所示
let url="http://192.169.201.32:9000//users/authenticate"
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(url, method: .post, parameters:["username":"andrews","password":"admin2"], encoding: URLEncoding.default)
.responseJSON { response in
print("abcsign in")
print(response)
print("abcsign in3")
print(response.result)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print("abcsign in 2")
print(JSON)
}
}
打印(响应)
FAILURE
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain = NSCocoaErrorDomain Code = 3840)“字符2周围的值无效。”UserInfo = {NSDebugDescription =字符2周围的值无效。})
print(response.result)
FAILURE
错误与响应状态:404
2)
第二个signUpviewcontroller.swift
与signUp
视图控制器相关联。在signUpViewController.swift
中,singUp webservice的代码如下所示
let url="http://192.169.201.32:9000//patient/signUp"
@IBAction func signUpButtonWasPressed(_ sender: Any) {
Alamofire.request(url, method: .post, parameters:["dob":DateOfBirthTextFeild.text ,
"email":emailIdTextField.text ,
"firstName":FirstNameTextField.text ,
"gender":genderTextField.text ,
"lastName":LastNameTextField.text ,
"middleName":MiddleNameTextField.text ,
"password":passwordTextField.text , //password must be 8 char long
"ssn":ssnTextField.text], encoding: URLEncoding.default)
.responseJSON { response in
print("abcsig up in")
print(response)
print("abcsign up in3")
print(response.result)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print("abcsign up in 2")
print(JSON)
}
}
}
打印(响应)输出是
FAILURE
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain = NSCocoaErrorDomain Code = 3840)“字符2周围的值无效。”UserInfo = {NSDebugDescription =字符2周围的值无效。})
print(response.result)
错误与响应状态:404
如何获得有效的json响应?
您可以从此链接下载项目。https://drive.google.com/file/d/1WjEng8RtRcuPOccTUHchDELIE1JSYlNW/view?usp=sharing 在postman上,api显示了所需的json out put。
提供正文中的参数。您可以添加将json url请求转换为post的.json参数。在下面的选项卡中,选择body,通过选择raw来将参数放在此处。
答案 0 :(得分:0)
答案 1 :(得分:0)
您是否尝试使用json编码而不是url编码?我注意到,在邮递员中,您使用原始数据作为正文发送了请求,并使用application/json
。
尝试更改Alamofire的请求方法,如下所示:
Alamofire.request(url, method: .post, parameters:["username":"andrews","password":"admin2"], encoding: JSONEncoding.default) // instead of URLEncoding.default