iosswifttableviewpopulate

populate fetched data to tableView using UISearchController


I am fetching data from an API and works fine when i type in a city in console. The problem i am facing now is with UISearchController and tableView in the code below i want to populate my searched city in the tableView. Now it does not show up anything when i run the app, except in my console that logs my request when a searched in the searchbar

LOG:

Search text: London
Creating request..
Task started
City name: London
Success! JSON decoded

This means using the searchfunction with the APIrequest works, except that I can't see it in my tableView.

Here is my 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: as this maybe can help someone to help me = API request handler

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

Solution

  • You need to update the filteredWeatherArray from the result you are getting from fetchCurrentWeather in your updateSearchResults(for searchController method, here's how:

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

    Edit: Even though the above code might work for you, you might not get the desired result. You are trying to display a list from the array of weatherArray, but when you make a call to fetchCurrentWeather you are getting just one result. I have modified my code to set the one array element to set as the weatherArray and reload.