我想使用状态在UITextView
上显示消息,但显示“成功:200”:
{“状态”:500,“信息”:“ \”信息无效\“”}
我在XCode10中使用Swift4,这是我的代码:
import UIKit
import Alamofire
import SwiftyJSON
class VerifyAccount: UIViewController {
let verify_url = "http://192.168.43.222:3000/mobile/account_verification"
@IBOutlet weak var msgHandler: UITextView!
func postData(url: String , parameters: [String : String]) {
Alamofire.request(url, method: .post, parameters: parameters).responseJSON {
response in
if response.result.isSuccess {
let postJSON : JSON = JSON(response.result.value!)
print(postJSON)
if let status = response.response?.statusCode {
switch(status) {
case 200:
self.msgHandler.text = ("Success: \(status)")
case 500:
self.msgHandler.text = ("Invalid: \(status)")
default:
}
}
} else {
print("Error: \(String(describing: response.result.error))")
}
}
}
@IBAction func verifyBtn(_ sender: Any) {
let compare : [String : String] = ["id" : id , "fname" : fname , "lname" : lname]
postData(url: verify_url , parameters : compare)
}
}
答案 0 :(得分:0)
您可以像这样从您的String
对象中安全地获取值(无论是Int
,JSON
等)>
let status = postJSON["status"].int ?? 0
let message = postJSON["msg"].string ?? "No Message"
(??)双问号使您能够提供默认值,以防您的解析未能获得Int
或String
答案 1 :(得分:0)
您需要更改处理回复的方式。我已经更新了您的代码,它应该可以正常工作。
import UIKit
import Alamofire
import SwiftyJSON
class VerifyAccount: UIViewController {
let verify_url = "http://192.168.43.222:3000/mobile/account_verification"
@IBOutlet weak var msgHandler: UITextView!
func postData(url: String , parameters: [String : String]) {
Alamofire.request(url, method: .post, parameters: parameters).responseJSON {
response in
switch response.result {
case .success:
print("server response: \(response.value!)")
do {
if var json = try JSONSerialization.jsonObject(with: response.data!, options: []) as? [String:Any] {
// Get value by key
var message = "";
if let msg = json["msg"] as? String
{
message = msg; // your message is here, you can do anything with it, whatever you want.
}
var status = 0;
if let st = json["status"] as? Int
{
status = st;
}
}
} catch let error as NSError {
}
break
case .failure(let error):
self.delegate.APIOnError(requestCode: requestCode);
print("server error: \(error.localizedDescription)")
}
}
}
答案 2 :(得分:0)
像这样解析您的响应数据
guard data _ = response.result.value as? [String: Any] else {
print("Error: \(String(describing: response.result.error))")
return
}
let message = data["msg"] as? String ?? "Unable to parse message"
if let statusCode = data["status"] as? Int {
switch statusCode {
case 200: self.msgHandler.text = ("Success: \(message)")
case 500: self.msgHandler.text = ("Invalid: \(message)")
default:self.msgHandler.text = ("Invalid status code")
}
}
答案 3 :(得分:0)
您使用错误的数据进行了解析。您可以尝试以下方法:
if let status = response.response?.statusCode, let message = postJSON['msg'] {
switch(status) {
case 200:
self.msgHandler.text = ("Success: \(message)")
case 500:
self.msgHandler.text = ("Invalid: \(message)")
default:
}
}