邮差中的我的JSON响应看起来像这样......
{
"success": 1,
"Details": {
"seller_id": "165",
"mobile_no": "9653265987",
"seller_name": "User A",
"seller_email_id": "user@gmail.com",
"company_name": "myCompany",
"category": "Cosmetics",
"otp": "1111"
},
"message": "Seller Already Registered!!!"
}
现在我想根据成功是0还是1给出一个条件,因此我想提取成功。另外我想提取手机号码。但我无法弄清楚如何做到这一点。
这就是我提出Alamofire邮寄请求的方式......
Alamofire.request(url, method: .post, parameters: Parameters, encoding: URLEncoding.httpBody, headers: headers)
.responseString { (response) in
if let httpResponse = response.response {
print("error \(httpResponse.statusCode)")
if httpResponse.statusCode == 200 {
//Do something
}
}
}
我确实经历过其他用户提出的类似问题......但无法从他们那里找到我的问题的确切解决方案......
答案 0 :(得分:2)
试试这个
Alamofire.request(url, method: .post, parameters: Parameters, encoding: URLEncoding.httpBody, headers: headers)
.responseJSON { (response) in
switch response.result{
case .success(_):
print("Success: \(response)")
let JsonResponse = response.result.value as? [String: Any]
if JsonResponse?["success"] as! Int == 1{
let dict = JsonResponse?["Details"] as! [String : Any]
let mobileNo = dict["mobile_no"] as! String
}
else{
print("Failed")
}
case .failure(let error):
print("Failed: \(error)")
}
}
答案 1 :(得分:0)
有几个问题:
request
的参数看起来不太合适。
parameters
参数看起来不正确:充其量,拥有Parameters
变量很奇怪(你应该使用小写变量;这与Alamofire类型冲突);
编码应为URLEncoding.default
。或者,因为URLEncoding.default
是的默认值,您可以完全省略它。
如果您想查看状态代码,请validate
为您执行此操作。
如果您希望回复JSON,请使用reponseJSON
代替responseString
。
使用if let
或guard let
与as?
安全地展开选项。不要使用as!
(除非你100%确定它永远不会失败......当处理来自远程服务器的响应时,你永远不会100%自信)。
因此:
func performRequest(url: String, parameters: [String: String]?, headers: [String: String]?) {
Alamofire.request(url, method: .post, parameters: parameters, headers: headers)
.validate(statusCode: 200 ..< 300)
.responseJSON { response in
switch response.result {
case .success(let value):
guard let dictionary = value as? [String: Any],
let success = dictionary["success"] as? Int else {
print("success not found")
return
}
guard success == 1 else {
print("web service reported failure")
return
}
guard let details = dictionary["Details"] as? [String: Any] else {
print("Did not find details")
return
}
guard let mobile = details["mobile_no"] as? String else {
print("mobile not found")
return
}
print(mobile)
case .failure(let error):
print("Failed: \(error)")
}
}
}
或者,在下面的评论中,如果您希望goToSignUpScreen()
success
为0
,那么:
Alamofire.request(url, method: .post, parameters: parameters, headers: headers)
.validate(statusCode: 200 ..< 300)
.responseJSON { response in
switch response.result {
case .success(let value):
guard let dictionary = value as? [String: Any],
let success = dictionary["success"] as? Int else {
print("success not found")
return
}
if success == 0 {
self.goToSignUpScreen()
}
case .failure(let error):
print("Failed: \(error)")
}
}