Swift 完成处理程序在完成之前为True
所以我有一个函数,它从API中获取引用和作者。我有一个完成处理程序,这样我就可以获得quote和author,然后在Viewdidload函数中将它们设置为各自的UILabel。但由于某种原因,引用和作者都是零。处理程序出了什么问题Swift 完成处理程序在完成之前为True,swift,xcode,completionhandler,Swift,Xcode,Completionhandler,所以我有一个函数,它从API中获取引用和作者。我有一个完成处理程序,这样我就可以获得quote和author,然后在Viewdidload函数中将它们设置为各自的UILabel。但由于某种原因,引用和作者都是零。处理程序出了什么问题 func getJSON(completionHandler: @escaping(CompletionHandler)){ if let quoteURL = URL(string: "http://quotes.rest/qod.json")
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()中调用函数
Swift不允许在后台进程中设置UILabel文本,这就是我无法在getJSON()中设置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
completionHandler(true) // set it inside the callback
}
else {
completionHandler(false)
}
}
task.resume()
}
else {
completionHandler(false)
}
}
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
}
else {
completionHandler(false)
}
}
task.resume()
}
else {
completionHandler(false)
}
}