提高搜索速度结果 - swift tableviewcontroller

时间:2017-06-08 10:27:02

标签: swift xcode uitableview search

我正在构建个人天气应用程序,用户可以在这里挑选城市并显示天气温度。

我在这个JSON文件中使用搜索:

cities.json

我使用以下代码进行搜索:

搜索扩展名:

extension SearchUI: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
    filterContentForSearchText(searchText: searchController.searchBar.text!)
}

过滤功能:

func filterContentForSearchText(searchText: String) {
    filteredCountries = countries.array!.filter { country in
        return country["name"].stringValue.lowercased().hasPrefix(searchText.lowercased())
    }
    tableView.reloadData()
}

我的cellForRowAt函数:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "countryCell")


    var data: JSON

    if searchController.isActive && searchController.searchBar.text != "" {
        data = filteredCountries[indexPath.row]
    } else {
        data = countries[indexPath.row]
    }

    let countryName = data["country"].stringValue
    let countrycity = data["name"].stringValue
    //data1.append(data["name"].stringValue)
    cell?.textLabel?.text = countrycity
    cell?.detailTextLabel?.text = countryName

    return cell!
}

我的应用程序中的搜索过程非常缓慢,并且在过滤过程中我面临键盘输入缓慢。

通知: countries - 是一个JSON对象

谢谢大家!

1 个答案:

答案 0 :(得分:0)

解析:

countries = try! JSON(data: NSData(contentsOfFile: Bundle.main.path(forResource: "cities_with_countries", ofType: "json")!)! as Data)