2017-05-09 48 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 
    } 
}