Search code examples
iosswiftsearchbar

How do i navigate to another view from search results displayed in table view?


The following code is my viewController code. The words from the json file are displayed in a tableView on click of a word it is taken to another page where elements associated with that word are displayed. However i am not able to navigate to that page when the search results are displayed in table view.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating{

@IBOutlet weak var mainTableView: UITableView!

var words = [wordStats]()
var filteredArray = [wordStats]()
var searchController = UISearchController()
var resultsController = UITableViewController()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    getJson {
        self.mainTableView.reloadData()
    }

    mainTableView.delegate = self
    mainTableView.dataSource = self

    searchController = UISearchController(searchResultsController: resultsController)
    mainTableView.tableHeaderView = searchController.searchBar
    searchController.searchResultsUpdater = self

    resultsController.tableView.delegate = self
    resultsController.tableView.dataSource = self

}

func updateSearchResults(for searchController: UISearchController) {
    filteredArray = words.filter({ (words: wordStats) -> Bool in
        if words.word.contains(searchController.searchBar.text!){
            return true
        }else{
            return false
        }
    })
    resultsController.tableView.reloadData()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if tableView == resultsController.tableView{
        return filteredArray.count
    }else{
        return words.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
    if tableView == resultsController.tableView{
        cell.textLabel?.text = filteredArray[indexPath.row].word.capitalized
    }else{
        cell.textLabel?.text = words[indexPath.row].word.capitalized
    }
    //cell.textLabel?.text = words[indexPath.row].word.capitalized
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "wordDetails", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? HeroViewController{
            destination.word = words[(mainTableView.indexPathForSelectedRow?.row)!]
        }
}

func getJson(completed: @escaping () -> ()){
    let path = Bundle.main.path(forResource: "week_14", ofType: "json")
    let url = URL(fileURLWithPath: path!)
    let data = try! Data(contentsOf: url)
            do {
                self.words = try JSONDecoder().decode([wordStats].self, from: data)
                DispatchQueue.main.async{
                    completed()
                }
            }catch{
                print("JSON error")
            }
}

}

Initially after getting the data from the JSON file the data is displayed in mainTableView but after searching when i click on the item app crashes. Can someone help me out please?

struct wordStats:Decodable{
let word: String
let synonym: String
let meaning: String
let example: String
let video: String

}

this is the wordStats


Solution

  • This is what worked in the end

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? HeroViewController {
            if let indexPath = mainTableView.indexPathForSelectedRow{
                if isFiltering(){
                    destination.word = filteredArray[indexPath.row]
                }else{
                    destination.word = words[indexPath.row]
                }
            }
        }
    }