刚刚开始快速倾斜。
WKWebView立即加载网站,无需等待。
下面的代码几乎可以工作,但实际上效果不佳。
由于UILable需要很长时间从网络加载数据,因此数据是非常示例的字符串文本,网络速度非常好。
有没有一种优雅的方式来做到这一点?
谢谢!
ViewController 类:UIViewController {
////Create a UILable labTitle dynamically////
var labTitle = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
labTitle = UILabel(frame: CGRect(x: 30, y: 30, width: 200, height: 20))
view.addSubView(labTitle)
////fetching the data from url////
URLSession.shared.dataTask(with: (NSURL(string: "www.abc.org/interface/") as URL?)!, completionHandler: {(data, response, error) -> Void in
if error != nil || data == nil {
print("Client error!")
return
}
do {
let js = try JSONSerialization.jsonObject(with: data!, options: [])
////give the string value to labTitle Text property////
self.labTitle.text = ((js as AnyObject)["REMOTE_ADDR"] as? String)!
} catch {
print("JSON error: \(error.localizedDescription)")
}
}).resume()
}
}
最佳答案
您需要DispatchQueue.main.async
,因为 session 回调位于后台线程中
let js = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
DispatchQueue.main.async {
self.labTitle.text = js["REMOTE_ADDR"] as? String
}
关于Swift 动态创建 UILabel 以使用网络数据字符串作为 Text 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58559967/