Update TableView from Asynchronous Data in Swift

时间:2015-07-14 19:33:56

标签: ios iphone json swift

I'm currently working on an iOS Application and I recently came across the issue that I was downloading and parsing data synchronously and as a result making the app completely unresponsive.

I've updated my code to download my data and parse it asynchronously however I'm now hitting another issue.

I've been trying to split my code up and follow the MVC pattern. I have my TableViewController as the delegate and DataSource of the TableView. I have another class that is managing downloading+parsing my data.

My issue is, once the data is parsed - how do I update the TableView since it's all being done asynchronously.

TableViewController

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
println(searchBar.text)

searchBar.resignFirstResponder() //Hide the keyboard

let result = ShowsDataParser.newSearchShows(searchBar.text) //Get search result based on input
searchResults = result.results
maxPages = result.maxPages
currentPage = 1
self.tableView.reloadData()
}

I've implemented all required methods(e.g cellForRowAtIndexPath) within this class too.

ShowsDataParser

class func newSearchShows(input: String, page:Int = 1) -> (results:[Show], maxPages: Int)
{
let searchUrl = "/search/tv" //Search URL
var searchResults = [Show]()
var totalPages = 1

let posterSize = "w92"

if let escapedSearch = escapeString(input) {
    var search = apiLocation + searchUrl + "?query=" + escapedSearch + "&api_key=" + APIKey + "&page=\(page)"

    if let url = NSURL(string: search)
    {
        let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler:{data,response,error -> Void in
            if let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
            {
                var name: String
                var id: Int
                var status: String
                var overview = "meow"
                if let results = json["results"] as? NSArray
                {
                    for result in results
                    {
                        id = result["id"] as! Int
                        name = result["original_name"] as! String
                        //overview = result["overview"] as! String
                        status = ""
                        var newShow = Show(showId: id, showName: name, showDesc: overview, showStatus: status)
                        if let date = result["first_air_date"] as? String
                        {
                            newShow.firstAired = self.formatDate(date)
                        }
                        if let poster = result["poster_path"] as? String
                        {
                            if let baseUrl = AppDelegate.config?.baseUrl
                            {
                                if let data = NSData(contentsOfURL: NSURL(string: baseUrl + posterSize + poster)!)
                                {
                                    //newShow.posterImage = UIImage(data: data)
                                }
                            }
                        }
                        searchResults.append(newShow)
                    }
                }
                if let pages = json["total_pages"] as? Int
                {
                    totalPages = pages
                }
            }

        })
    }

}

return (results: searchResults, maxPages: totalPages)
}

As you can see, the above class gets and parses the data from the specified url. I'm simply unsure of how to update the tableview after this is done. Calling upon self.tableView.reloadData() within searchBarSearchButtonClicked isn't working.

1 个答案:

答案 0 :(得分:3)

在if语句

之后放置reloadData()调用
if let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{ 

.... more code 

    if let pages = json["total_pages"] as? Int
    {
        totalPages = pages
    }
}
self.myTableView.reloadData()