Swift: tableView.reloadData () is too slow
I am trying to make a call tableView.reloadData()
after an async request that I am calling to populate mine UITableView
. The table displays the data in 15-20 seconds, unless I manually start scrolling, in which case everything loads immediately. So the data is definitely there, it just isn't loading properly. What can I do to fix this problem?
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
}
}
}
})
}
}
source to share
The problem is what you are installing jsonLoaded
on a background thread. This means it is reloadData()
also called on a background thread. But you should never talk to an interface on a background thread! You need to exit to the main thread before doing anything that has to do with general data (like jsonLoaded
) or interface.
source to share