For some reason when I type in the search field it does not print out Xcode console the "str". What am I missing here? I followed his tutorial https://www.letsbuildthatapp.com/course_video?id=5232
import UIKit
class SearchViewController: UIViewController {
let searchController = UISearchController(searchResultsController: nil)
var sink: Any?
override func viewDidLoad() {
super.viewDidLoad()
setupSearchBarListener()
navigationItem.searchController = searchController
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.title = "Contact"
searchController.obscuresBackgroundDuringPresentation = false
view.backgroundColor = .white
}
fileprivate func setupSearchBarListener() {
let publisher = NotificationCenter.default.publisher(for: UISearchTextField.textDidChangeNotification, object: searchController.searchBar.searchTextField)
publisher
.map {
($0.object as! UISearchTextField).text
}
.debounce(for: .milliseconds(500), scheduler: RunLoop.main)
.sink { (str) in
print(str ?? "")
}
}
}
You are creating a Sink object with the .sink
method, but you are not storing it anywhere. Therefore it goes out of existence immediately and there is no pipeline to publish to.
The correct procedure here is to have an instance property typed as Set<AnyCancellable>
and call store(in:)
on your sink to store it in that instance property. Now it will persist and there will be something to print out.