2017-05-09 93 views
0

我的JSON“R1”返回1或0.使用1我想让我的标签变成蓝色。我在代码中做错了什么?根据来自JSON的值更改标签的颜色

myJson = { 
    "product": "IPX800_V4", 
    "R1": 0, 
    "R2": 0, 
    "R3": 0, 
    "R4": 0, 
    "R5": 0, 
    "R6": 0, 
    "R7": 0, 
    "R8": 0, 
    "R9": 0, 
    "R10": 0, 
    "R11": 0, 
    "R12": 0, 
    "R13": 0, 
    "R14": 0, 
    "R15": 0, 
} 

从显示器的解析工作在0和1

我的标签被称为led1,应该变成蓝色,当 “R1”= 1

class ViewController: UIViewController { 
    @IBOutlet weak var led1: UILabel! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let url = URL(string: "http://192.168.1.201/api/xdevices.json?key=apikey&Get=R") 
     let task = URLSession.shared.dataTask(with: url!) { (data, respense, error) in 
      if error != nil 
      { print("error") } 
      else 
      { 
       if let content = data 
       { 
        do 
        { 
         let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject 

         let r1 = myJson["R1"] 
         if let r1 = myJson["R1"] { print(r1!) } 
         if (r1 > 0) { self.led1.backgroundColor = UIColor.blue } 
        } 
        catch {  
        } 
       } 
      } 
     } 
     task.resume() 
    } 
} 
+0

您的标签是否连接到故事板? – Retterdesdialogs

+0

请在您的问题中包含预期的JSON响应。您的代码不起作用,因为您将JSON解析为单个AnyObject。我无法告诉你如何解析它而不看到你期望的JSON,但AnyObject不是正确的方式。 –

+0

我的JSON:{ “产品”: “IPX800_V4”, “R1”:0, “R2”:0, “R3”:0, “R4”:0, “R5”:0, “R6”:0, “R7”:0, “R8”:0, “R9”:0, “R10”:0, “R11”:0, “R12”:0, “ R13“:0, ”R14“:0, ”R15“:0,} –

回答

1

你需要更新UI在主线程上。在Swift 3中:

if (r1 > 0) { 
    DispatchQueue.main.async { 
     self.led1.backgroundColor = UIColor.blue 
    } 
}