简体   繁体   English

从Swift中的异步数据更新TableView

[英]Update TableView from Asynchronous Data in 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. 我目前正在开发一个iOS应用程序,最近我遇到了我正在下载和同步解析数据的问题,结果使应用程序完全没有响应。

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. 我一直在尝试拆分我的代码并遵循MVC模式。 I have my TableViewController as the delegate and DataSource of the TableView. 我有我的TableViewController作为TableView的委托和DataSource。 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. 我的问题是,一旦数据被解析 - 我如何更新TableView,因为它是异步完成的。

TableViewController 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(eg cellForRowAtIndexPath) within this class too. 我也在这个类中实现了所有必需的方法(例如cellForRowAtIndexPath)。

ShowsDataParser 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. 如您所见,上面的类获取并解析来自指定url的数据。 I'm simply unsure of how to update the tableview after this is done. 在完成此操作后,我只是不确定如何更新tableview。 Calling upon self.tableView.reloadData() within searchBarSearchButtonClicked isn't working. searchBarSearchButtonClicked调用self.tableView.reloadData()不起作用。

place the reloadData() call after the if statement 在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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM