所以我有一个从API获取报价和作者的函数。我有一个完成处理程序,以便我可以获取报价和作者,然后在Viewdidload函数中将它们设置为各自的UILabel。但是由于某种原因,引号和作者都为零。处理程序出了什么问题?
func getJSON(completionHandler: @escaping(CompletionHandler)){
if let quoteURL = URL(string: "http://quotes.rest/qod.json")
{
let session = URLSession.shared
let task = session.dataTask(with: quoteURL)
{ (data, response, error) -> Void in
if data != nil
{
let quoteData = JSON(data: data!)
self.quote = quoteData["contents"]["quotes"][0]["quote"].stringValue
self.author = quoteData["contents"]["quotes"][0]["author"].stringValue
}
}
task.resume()
}
completionHandler(true)
}
在Viewdidload()中调用函数
self.getJSON(completionHandler: {(success)-> Void in
if(success){
self.quoteLabel.text = "\(self.quote ?? "") - \(self.author ?? "")"
}
})
Swift不允许您在后台进程中设置UILabel文本,这就是为什么我无法在getJSON()中进行设置的原因谢谢
您需要将其插入回调中
func getJSON(completionHandler: @escaping(CompletionHandler)){
if let quoteURL = URL(string: "http://quotes.rest/qod.json")
{
let session = URLSession.shared
let task = session.dataTask(with: quoteURL)
{ (data, response, error) -> Void in
if data != nil
{
let quoteData = JSON(data: data!)
self.quote = quoteData["contents"]["quotes"][0]["quote"].stringValue
self.author = quoteData["contents"]["quotes"][0]["author"].stringValue
completionHandler(true) // set it inside the callback
}
}
task.resume()
}
}