【发布时间】:2018-05-22 11:00:19
【问题描述】:
1)
我是使用 alamofire 的新手。这是我尝试使用 alamofire 来检查我错在哪里的 web 服务。我在 loginviewcontroller.swift 中创建了一个登录 web 服务,如下所示
let url="http://192.169.201.32:9000//users/authenticate"
@IBAction func DoLogin(_ sender: AnyObject) {
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)
}
}
if(login_button.titleLabel?.text == "Logout")
{
let preferences = UserDefaults.standard
preferences.removeObject(forKey: "session")
LoginToDo()
}
else{
login_now(username:username_input.text!, password: password_input.text!)
}
}
打印(响应)
失败
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailu>reReason.jsonSerializationFailed(错误 Domain=NSCocoaErrorDomain Code=3840 "字符周围的值无效 2." UserInfo={NSDebugDescription=字符 2.}))
打印(response.result)
失败
error with response status: 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 ")
print(response)
print("abcsign up 3")
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)
}
}
}
打印(响应)
失败
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailu>reReason.jsonSerializationFailed(错误
Domain=NSCocoaErrorDomain Code=3840 "字符周围的值无效 2." UserInfo={NSDebugDescription=字符 2.}))
打印(response.result)
响应状态错误:404
如何获得有效的 json 响应?
您可以从此链接下载项目https://drive.google.com/file/d/1Q__ydaQ7o0fKcFHdq6ymkxh52IEf7hMK/view?usp=sharing 在 postman 上,api 显示了所需的 json 输出。
注册:
登录:
在body中提供参数。您可以添加将 json url 请求转换为 post 的 json 参数。在下面的选项卡中选择 body 通过选择 raw 将参数放在这里。
【问题讨论】:
-
使用
JSONEncoding,不要使用//,请求url中只需要一个/。
标签: ios json swift web-services alamofire