使用UISearchController将获取的数据填充到tableView中。

问题描述 投票:0回答:1

我正在从API中获取数据,当我在控制台中输入一个城市时,工作正常。我现在面临的问题是UISearchController和tableView,在下面的代码中,我想在tableView中填充我搜索的城市。现在,当我运行应用程序时,除了在我的控制台中记录我在搜索栏中搜索时的请求外,没有任何显示。

LOG.这意味着使用APIrequest的搜索函数可以工作,只是我在我的tableView中看不到它。 Search text: London Creating request.. Task started City name: London Success! JSON decoded

这意味着使用APIrequest的searchfunction可以工作,只是我不能在我的tableView中看到它。

这是我的viewController

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
 }
}

EDIT: 因为这也许可以帮助别人来帮助我=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")
    }
ios swift api tableview populate
1个回答
0
投票

你需要更新 filteredWeatherArray 从你得到的结果 fetchCurrentWeather 在你 updateSearchResults(for searchController 方法,这里是如何。

mWeather.fetchCurrentWeather(city: searchText) { weather in
    self.weatherArray = [weather]
    DispatchQueue.main.async {
        self.tableView.reloadData()
    }
}

编辑: 尽管上面的代码可能对你有用, 但你可能得不到想要的结果. 你正试图从数组中显示一个列表,该数组中的 weatherArray但当你打电话给 fetchCurrentWeather 你只得到一个结果。我已经修改了我的代码,将一个数组元素设置为 weatherArray 并重新加载。

© www.soinside.com 2019 - 2024. All rights reserved.