Avelyn Hyunjeong Choi
Posted on November 15, 2023
In this blog, I will try to extend the app we built in Part I by adding a search bar in the Main View Controller so that you type in the search bar and it will filter the employees based on the name, age or phone. I will also add other entities and add relationships between these entities.
In MainVC
, add setupSearchBar()
to add the searchBar in UI.
import UIKit
class MainVC: UIViewController {
...
private let searchBar = UISearchBar()
override func viewDidLoad() {
...
setupSearchBar()
}...
}
In extension MainVC
, searchBar related functions are implemented as below.
extension MainVC: UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
private func setupSearchBar() {
searchBar.placeholder = "Search Employees"
navigationItem.titleView = searchBar
searchBar.delegate = self
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
empArray = CoreDataHandler.shared.fetchData()
} else {
empArray = CoreDataHandler.shared.searchData(with: searchText)
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
searchBar.resignFirstResponder()
empArray = CoreDataHandler.shared.fetchData()
}
...
Lastly, add searchData()
in CoreDataHandler
to retrieve data matching the user's input
class CoreDataHandler {
...
func searchData(with searchText: String) -> [Emp] {
let fetchRequest: NSFetchRequest<Emp> = Emp.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "name CONTAINS[c] %@ OR age == %@ OR phone CONTAINS[c] %@", searchText, searchText, searchText)
do {
let result = try context!.fetch(fetchRequest)
return result
} catch {
print("Failed to search employees")
return []
}
}
}
Result
Add other entities and add relationships between these entities.
Full code is available in employeeCatalogue
💖 💪 🙅 🚩
Avelyn Hyunjeong Choi
Posted on November 15, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.