在tableView swift4中搜索JSON数据

时间:2018-10-31 06:31:39

标签: ios swift uisearchbar

我试图将jsondata显示在tableView中,并从country搜索searchBar,但将error插入textDidChange功能。

我希望用户在searchBar中输入三个词,然后tableView将打开并搜索数据。

struct country : Decodable {
    let name : String
    let capital : String
    let region : String
  }

class ViewController: UIViewController,UISearchBarDelegate {

    var isSearch : Bool = false
    var countries = [country]()
    var arrFilter:[String] = []

    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var searchbar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableview.dataSource = self
        tableview.delegate = self
        searchbar.delegate = self

        let jsonurl = "https://restcountries.eu/rest/v2/all"
        let url = URL(string: jsonurl)

        URLSession.shared.dataTask(with: url!) { (data, response, error) in

            do{
                self.countries = try JSONDecoder().decode([country].self, from: data!)

            }
            catch{
                print("Error")
            }
            DispatchQueue.main.async {
                self.tableview.reloadData()
            }
            }.resume()
}

在此部分显示错误。

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

    if searchText.characters.count == 0 {
        isSearch = false;
        self.tableview.reloadData()
    } else {
        arrFilter = countries.filter({ (text) -> Bool in
            let tmp: NSString = text
            let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
            return range.location != NSNotFound
        })
        if(arrFilter.count == 0){
            isSearch = false;
        } else {
            isSearch = true;
        }
        self.tableview.reloadData()
    }
  }

}

我的表格视图部分

extension ViewController : UITableViewDelegate, UITableViewDataSource{
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if(isSearch){
       return arrFilter.count
    }
    else{
      return countries.coun
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    if(isSearch){    
         cell.textLabel?.text = arrFilter[indexPath.row]    
    }else{
         cell.textLabel?.text = countries[indexPath.row].name.capitalized
    }
    return cell
  }
}

3 个答案:

答案 0 :(得分:2)

  • 首先不要在Swift中使用NSString Foundation rangeOfString API,而要使用本地String和本地{{1} }。
  • 所有第二个从不检查空字符串和带有range(of的空数组。有.count == 0
  • 请在所有第三项中以首字母大写来命名结构和类。 isEmpty

发生错误是因为您正在过滤struct Country ...个实例,而实际上是在寻找其Countryname

这是您代码的纯Swift版本

region

如果您要过滤func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { isSearch = false } else { arrFilter = countries.filter( $0.name.range(of: searchText, options: .caseInsensitive) != nil } isSearch = !arrFilter.isEmpty } self.tableview.reloadData() } name

region

使用此语法声明arrFilter = countries.filter( $0.name.range(of: searchText, options: .caseInsensitive) != nil || $0.region.range(of: searchText, options: .caseInsensitive) != nil }

arrFilter

并在var arrFilter = [Country]() 中写

cellForRow

答案 1 :(得分:0)

您正在以字符串的形式获取数组的国家对象,因此发生了这样的错误。 请执行以下操作

    var arrFilter:[country] = [country]()

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if(isSearch){    
        cell.textLabel?.text = arrFilter[indexPath.row].name.capitalized    
        }else{
             cell.textLabel?.text = countries[indexPath.row].name.capitalized
        }
        return cell
    }


    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
            if searchText.characters.count == 0 {
                isSearch = false;
                self.tableview.reloadData()
            } else {
                arrFilter = countries.filter({ (country) -> Bool in

                    let tmp: NSString = NSString.init(string: country.name)
                    let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)

                    return range.location != NSNotFound
                })
                if(arrFilter.count == 0){
                    isSearch = false;
                } else {
                    isSearch = true;
                }
                self.tableview.reloadData()
            }
     }

答案 2 :(得分:0)

首先,您不能将[Country]的值类型分配给[String]。例如,当在那时分配arrFilter country.filter总是返回国家类型的值而不是字符串类型。

使用以下代码来帮助您

var countries = [country]()
var arrFilter:[country] = [country]()

在viewdidLoad内

override func viewDidLoad() {

    self.countries.append(country(name: "India", capital: "New Delhi", region: "Asia"))
    self.countries.append(country(name: "Indonesia", capital: "Jakarta", region: "region"))
    self.countries.append(country(name: "Australia", capital: "Canberra", region: "Austrialia"))
    // Do any additional setup after loading the view.
}

 self.arrFilter = self.countries.filter({ (country) -> Bool in
        let temp : NSString  = country.name as NSString //or you can use country.capital or country.region
        let range = temp.range(of: "ind", options: .caseInsensitive)
        print(range.location)
        print(range.length)
        print(temp)
        return range.location != NSNotFound
    })

谢谢