Swift:更新标签/ HTTP请求

时间:2018-02-21 17:11:27

标签: swift xcode post httprequest

也许有人可以帮我找到问题的答案: 我向后端发送了一个post请求,后端是用Java和Playframework2创建的。 在我的xcode应用程序中,我可以创建一个用户,并且用户是否在数据库中,后端使用状态代码进行回复,我想在标签上显示该状态代码。 问题是状态代码的文本/状态总是“落后”。

所以我开始我的后端和我的xcode应用程序。 当我单击提交按钮时,它会将带有json数据的http请求激发到后端,并且创建用户并且状态代码为200条,但标签上没有显示。 当我再次点击模具提交按钮(同一个人试图创建)时,409被响应。 但现在,lable shwos是之前发送的200个请求。

有人知道吗?

class ViewController: UIViewController {

@IBOutlet var tfEmail: UITextField!

@IBOutlet var tfUsername: UITextField!

@IBOutlet var tfPW: UITextField!

var ret: String = "app loaded";
@IBOutlet var label: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    print("Hello world");




}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func printMessage() -> Void {
    let json = ["email" : self.tfEmail.text!,
                "username" : self.tfUsername.text!,
                "password" : self.tfPW.text!] as [String : Any];

    do {

        let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted);

        let url = URL(string: "http://localhost:9000/save")!
        var request = URLRequest(url: url);

        request.httpMethod = "POST";
        request.setValue("application/json; charset=utf8", forHTTPHeaderField: "Content-Type");
        request.httpBody = jsonData;

        let task = URLSession.shared.dataTask(with: request) {
            data, response, error in
            if error != nil {
                print("Error -> \(String(describing: error))");
                self.ret = "\(String(describing: error))";
            }
            if let httpResponse = response as? HTTPURLResponse {
                print("statusCode: \(httpResponse.statusCode)");
                if(httpResponse.statusCode == 200) {
                    self.ret = "success \(httpResponse.statusCode)"
                } else {
                    self.ret = "error \(httpResponse.statusCode)"
                }
            }
        }

        task.resume();
    } catch {
        print(error);
    }

}

@IBAction func postButton(_ sender: Any) {

    printMessage()
    label.text = self.ret;


}

}

1 个答案:

答案 0 :(得分:0)

主要问题是您在按下按钮时设置了标签文字,而不是在获得所需的值之后。更改您的代码:

if let httpResponse = response as? HTTPURLResponse {
                print("statusCode: \(httpResponse.statusCode)");
                if(httpResponse.statusCode == 200) {
                    self.ret = "success \(httpResponse.statusCode)"
                    doLabelChange()
                } else {
                    self.ret = "error \(httpResponse.statusCode)"
                    doLabelChange()
                }




func doLabelChange() {
    DispatchQueue.main.async {
           self.label.text = self.ret
        }
}