How to use searchController with searchResultsController?

333 Views Asked by At

I created a search controller and added a searchResultsController to it.

MainController.swift

let searchController = UISearchController(searchResultsController: SearchResultVC())

My search logic works within the updateSearchResults method and this is triggered every time a search is made. This, of course, is provided by the UISearchResultsUpdating protocol. Here I will add the list I am looking for to the data of the tableView in SearchResultVC and reload the tableView.

MainController.swift

func updateSearchResults(for searchController: UISearchController) {

    guard let searchText = searchController.searchBar.text else { return }

    if let vc = searchController.searchResultsController as? SearchResultVC {
       vc.searchText = searchText
       vc.reminderList = search(searchText: searchText)
       if let vcTableView = vc.searchTableView { // HERE ISN'T TRIGGERED
          vcTableView.dataSource = vc
          vcTableView.delegate = vc
          vcTableView.reloadData()
          print("reloaded")
       }
    }
}

Finally, I will show my data in the newly opened searchViewController.

SearchResultVC.swift

final class SearchResultVC: UIViewController {

    var reminderList: [ReminderList] = []
    var searchText: String?

    @IBOutlet weak var searchTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.searchTableView.delegate = self // HERE IS CRASHED
        self.searchTableView.dataSource = self // HERE IS CRASHED
    }
}

My problem is not being able to reload. The partition where reload () is located is not triggered. Also, the newly opened page is self.searchTableView.delegate = self and self.searchTableView.dataSource = self crashed.

How can I trigger vcTableView.reloadData() correctly ?

EDIT

This error occurs. enter image description here

0

There are 0 best solutions below