ios - 使用 UISearchController 将获取的数据填充到 tableView
问题描述
我正在从 API 获取数据,并且当我在控制台中输入城市时工作正常。我现在面临的问题是下面代码中的 UISearchController 和 tableView 我想在 tableView 中填充我搜索的城市。现在,当我运行应用程序时它不会显示任何内容,除了在我的控制台中,当在搜索栏中搜索时记录我的请求
日志:
Search text: London
Creating request..
Task started
City name: London
Success! JSON decoded
这意味着将搜索功能与 APIrequest 一起使用是可行的,但我在 tableView 中看不到它
这是我的视图控制器
import UIKit
class ViewController: UIViewController{
@IBOutlet weak var tblView: UITableView!
let mWeather = WeatherAPI()
var weatherArray = [WeatherStruct]()
var filteredWeatherArray : [String] = []
// dummy data
let originalArray = ["gothenburg", "london", "stockholm", "new york", "washington DC", "thailand", "china", "spain", "paris"]
var searching: Bool {
if weatherArray.count > 0 {
return true
} else {
return false
}
}
let searchController: UISearchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "type in your city here"
navigationItem.searchController = searchController
tblView.delegate = self
tblView.dataSource = self
}
}
// MARK: - extensions
extension ViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let searchText = searchController.searchBar.text ?? "can not search"
print("Search text: \(searchText)")
mWeather.fetchCurrentWeather(city: searchText) { (WeatherStruct) in}
tblView.reloadData()
}
}
// MARK: - Table view data source
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searching {
return weatherArray.count // when something is typed on searchbar
}else{
return filteredWeatherArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath)
if searching {
cell.textLabel?.text = weatherArray[indexPath.row].name
tblView.reloadData()
} else {
cell.textLabel?.text = filteredWeatherArray[indexPath.row]
tblView.reloadData()
}
return cell
}
}
编辑:因为这可能可以帮助某人帮助我= API请求处理程序
func fetchCurrentWeather(city: String, completionHandler: @escaping (WeatherStruct) -> Void) {
// url
let wholeUrl = baseUrlForCurrentWeather + city + appid + metric
let urlString = (wholeUrl)
guard let url: URL = URL(string: urlString) else { return }
// Request
print("Creating request..")
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let unwrappedError = error {
print("Nått gick fel. Error: \(unwrappedError)")
return
}
if let unwrappedData = data {
do {
let decoder = JSONDecoder()
let wdata: WeatherStruct = try decoder.decode(WeatherStruct.self, from: unwrappedData)
print("City name: \(String(describing: wdata.name))")
print("Success! JSON decoded")
completionHandler(wdata)
} catch {
print("Couldnt parse JSON..")
print(error)
}
}
}
// Starta task
task.resume()
print("Task started")
}
解决方案
您需要从您的方法filteredWeatherArray
中获得的结果中更新,方法如下:fetchCurrentWeather
updateSearchResults(for searchController
mWeather.fetchCurrentWeather(city: searchText) { weather in
self.weatherArray = [weather]
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
编辑:即使上面的代码可能对你有用,你可能不会得到想要的结果。您正在尝试显示 数组中的列表weatherArray
,但是当您拨打电话时,fetchCurrentWeather
您只会得到一个结果。我修改了我的代码以将一个数组元素设置为weatherArray
并重新加载。
推荐阅读
- reactjs - Redux Store 不获取图像文件
- jquery - 为什么我不能使用 jQuery 在 Wordpress 中定位存档下拉列表?
- web-scraping - Parsing and extracting data to pandas using BeautifulSoup
- elasticsearch - How to integrate spring data elastic search with DDD principles?
- ibm-cloud-infrastructure - Softlayer Virtual Guest - Invalid value provided for tags
- javascript - Importing ng-redux just returns a string
- c# - WPF Binding a collection of collections to a DataGrid
- c# - 将包含数据的大对象传递到接口中
- php - 坚持使用 PHP 和 Regex 为 MYSQL 准备 DHCP 输出
- html - VBA 粘贴到列 IF 单元格 x 中的日期等于列 y 中的日期