我尝试使用json制作旅行数据并添加UISearchController
。
看来我可以用英文和数字运行UISearchController
了;但是,键入关键字时无法搜索普通话。
这里是代码,感谢可以帮助我的人!
class TableViewController: UITableViewController, UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let searchString = searchController.searchBar.text!
filteredData = travelData.filter({ (data) -> Bool in
return (data.Name.contains(searchString) && data.Add.contains(searchString))
})
tableView.reloadData()
}
var travelData = [DetailData]()
var filteredData = [DetailData]()
override func viewDidLoad() {
super.viewDidLoad()
guard let url = "http://data.ntpc.gov.tw/api/v1/rest/datastore/382000000A-002491-001".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let downloadUrl = URL(string: url) else {return}
let task = URLSession.shared.dataTask(with: downloadUrl) { (data, response, error) in
let decoder = JSONDecoder()
print("Decoder")
if let data = data{
do{
let json = try decoder.decode(Alldata.self, from: data)
self.travelData = json.result.records
print("json")
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch{
print(error.localizedDescription)
}
}
}
task.resume()
navigationController?.navigationBar.prefersLargeTitles = false
let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
navigationItem.searchController = searchController
definesPresentationContext = true
navigationItem.hidesSearchBarWhenScrolling = false
let image = UIImage()
self.navigationController?.navigationBar.setBackgroundImage(image, for: .default)
self.navigationController?.navigationBar.shadowImage = image
}
}