我的JSON" R1"返回1或0.使用1我想让我的标签变蓝。我的代码中我做错了什么?
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 :(得分:1)
您需要更新主线程上的UI。在Swift 3中:
if ( r1 > 0) {
DispatchQueue.main.async {
self.led1.backgroundColor = UIColor.blue
}
}