swift 4 - backgroundColor和按钮标题不变

时间:2017-11-10 02:10:07

标签: ios swift multithreading asynchronous button

我有这段代码,当backgroundColor上的setTitle和标题(button)发生变化(在主队列下调度)时,没有任何反应。

//
//  ViewController.swift
//  HeaterControl
//
//  Created by Eamon White on 11/7/17.
//  Copyright © 2017 EamonWhite. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    var button:HeaterButton = HeaterButton();
    var message:String = "";
    var status:Int = 0;

    override func viewDidLoad() {
        super.viewDidLoad()

        let button:HeaterButton = HeaterButton();
        button.setTitle("LOADING...", for: .normal);
        button.addTarget(self, action:#selector(toggle), for: .touchUpInside);
        self.view.addSubview(button);

        self.getState();
        // Do any additional setup after loading the view, typically from a nib.
    }

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

    //GET STATE OF ESP8266
    private func getState() {

        let url = URL(string: "https://cloud.arest.io/w1zard/digital/2");
        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in

            guard let data = data, error == nil else { return }

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any];

                self.status = (json["return_value"] as? Int)!;
                print(self.status, ": status");

                if self.status == 0 {
                    DispatchQueue.main.async { // Correct
                        self.button.backgroundColor = .green;
                        self.button.setTitle("TURN OFF", for: .normal)
                    }
                }
                else {
                    DispatchQueue.main.async { // Correct
                        self.button.setTitle("TURN ON", for: .normal)
                    }
                }
            } catch let error as NSError {
                print(error);
            }

        }).resume()
    }

    @objc private func toggle() {

        let url = URL(string: "https://cloud.arest.io/w1zard/mode/2/o");
        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in

            guard let data = data, error == nil else { return }

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any];
                self.message = json["message"] as! String;
                print(self.message, ": message");

                if self.message == "Pin D2 set to output" {
                    if self.status == 0 {
                        let url = URL(string: "https://cloud.arest.io/w1zard/digital/2/1");
                        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in

                            guard let data = data, error == nil else { return }

                            do {
                                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any];
                                self.message = json["message"] as! String;
                                print(self.message, ": message");

                                if self.message == "Pin D2 set to 1" {
                                    DispatchQueue.main.async { // Correct
                                        self.button.backgroundColor = .green;
                                        self.button.setTitle("TURN OFF", for: .normal)
                                        self.status = 1;
                                    }
                                }
                                else {
                                    let alert = UIAlertController(title: "ALERT", message: "Didn't turn on.", preferredStyle: .alert)
                                    alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in
                                        print("The \"OK\" alert occured.")
                                    }))
                                    self.present(alert, animated: true, completion: nil)
                                }
                            } catch let error as NSError {
                                print(error);
                            }

                        }).resume()
                    }
                    else {
                        let url = URL(string: "https://cloud.arest.io/w1zard/digital/2/0");
                        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in

                            guard let data = data, error == nil else { return }

                            do {
                                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any];
                                self.message = json["message"] as! String;
                                print(self.message, ": message");

                                if self.message == "Pin D2 set to 0" {
                                    DispatchQueue.main.async { // Correct
                                        self.button.backgroundColor = .green;
                                        self.button.setTitle("TURN OFF", for: .normal)
                                    }
                                }
                                else {
                                    let alert = UIAlertController(title: "ALERT", message: "Something went wrong.", preferredStyle: .alert)
                                    alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in
                                        print("The \"OK\" alert occured.")
                                    }))
                                    self.present(alert, animated: true, completion: nil)
                                }
                            } catch let error as NSError {
                                print(error);
                            }

                        }).resume()
                    }
                }
                else {
                    let alert = UIAlertController(title: "ALERT", message: "Couldn't set mode.", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in
                        print("The \"OK\" alert occured.")
                    }))
                    self.present(alert, animated: true, completion: nil)
                }
            } catch let error as NSError {
                print(error);
            }

        }).resume()
    }
}

1 个答案:

答案 0 :(得分:0)

我两次声明button

class ViewController: UIViewController {
    var button:HeaterButton = HeaterButton();
    var message:String = "";
    var status:Int = 0;

    override func viewDidLoad() {
        super.viewDidLoad()

        let button:HeaterButton = HeaterButton();

...