我尝试在我要求填充tableView.reloadData()
的异步请求后执行UITableView
来电。该表显示15-20秒后的数据,除非我手动开始滚动,在这种情况下它会立即加载。所以数据肯定存在,它只是没有正确加载。我该怎么做才能解决这个问题?
var jsonLoaded:Bool = false {
didSet {
if jsonLoaded {
tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://www.googleapis.com/youtube/v3/search?part=id&q=\(searchTerm)&maxResults=1&key=AIzaSyD7PxAoq0O5hUxx775l_E_mnowlU4cUfcI")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
if let items = jsonResult["items"] as? NSArray {
for songs in items {
if let id = songs["id"] as? NSDictionary {
if let videoId = id["videoId"] as? String {
let newURL = NSURL(string: "https://www.googleapis.com/youtube/v3/search?relatedToVideoId=\(videoId)&part=snippet&type=video&maxResults=6&key=AIzaSyD7PxAoq0O5hUxx775l_E_mnowlU4cUfcI")
let newTask = NSURLSession.sharedSession().dataTaskWithURL(newURL!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let newJsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
if let info = newJsonResult["items"] as? NSArray {
for videos in info {
if let snippet = videos["snippet"] as? NSDictionary {
if let title = snippet["title"] as? String {
self.recommendedTitles.append(title)
self.jsonLoaded = true
}
}
}
}
})
newTask.resume()
}
}
}
jsonLoaded = false
}
}
}
})
}
}
答案 0 :(得分:4)
问题是您在后台线程上设置jsonLoaded
。这意味着在后台线程上也会调用reloadData()
。但是你必须从不在后台线程上与界面交谈!在执行涉及共享数据(例如jsonLoaded
)或接口的任何之前,您需要走出主线程。