[iOS]Making a Contact-like app using CoreData

I have recently learnt so much about iOS developing on Udemy online class which taught by Dr.Angela, and I thought it would be a great idea for me to utilize and practice what I learnt to make some things out of it. And since CoreData is one of the biggest challenges you can find in the course, it would be best that I start from here.

Here is a quick demo on what I did with this app.

So basically, this app can add a new contact using UIAlertController and UIAlertAction. After adding a new contact to the CoreData, you can see it on the list and press it to see the details on another ViewController where you can also alter the details about that person. I also added a searchBar to help users filter the contact. All in all, it contains all the CRUD(Create, Read, Update, Delete) operations for persistent storage.

CoreData

My data model is pretty simple. I only have one entity with three attributes(name, mobile, company).

Main List

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContextoverride func viewDidLoad() {super.viewDidLoad()loadContacts()tableView.tableFooterView = UIView(frame: CGRect.zero)}func loadContacts() {let request : NSFetchRequest<Contact> = Contact.fetchRequest()do {contacts = try context.fetch(request)}catch {print("Error fetching data: \(error)")}tableView.reloadData()}

The main view controller is where we load up our screen with our data. (I won’t bother you with the details on the tableView datasource and tableView delegate functions). To add a new contact, we want to use UIAlertController and UIAlertAction because it’s much simpler than adding a whole new ViewController to add new contact and pass it to our CoreData.

UIAlert

//MARK: - Add Button@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {let alert = UIAlertController(title: "Add New Contact", message: "", preferredStyle: .alert)//Add namealert.addTextField { name inname.placeholder = "Name"}//Add phone numberalert.addTextField { phone inphone.placeholder = "Mobile"}alert.addTextField { company incompany.placeholder = "Company"}let action = UIAlertAction(title: "Add", style: .default) { action inlet newContact = Contact(context: self.context)newContact.name = alert.textFields![0].textnewContact.mobile = alert.textFields![1].textif let companyText = alert.textFields?[2] {newContact.company = companyText.text}self.contacts.append(newContact)self.saveContacts()}let cancel = UIAlertAction(title: "Cancel", style: .default) { cancel inprint("Cancel")}alert.addAction(action)alert.addAction(cancel)present(alert, animated: true, completion: nil)}}
func saveContacts(){
do{try context.save()}catch {print("Error saving data: \(error)")}tableView.reloadData() }

UISearchBar

Adding the searchBar is a little bit tricky. The NSPredicate is not similar to swift syntax. But we can find more information on these websites:

extension ContactsTableViewController: UISearchBarDelegate {func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {let request : NSFetchRequest<Contact> = Contact.fetchRequest()let predicate = NSPredicate(format: "name CONTAINS[cd] %@", searchBar.text!)request.predicate = predicaterequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]do {contacts = try context.fetch(request)} catch {print("Error fetching data: \(error)")}tableView.reloadData()}func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {if searchBar.text?.count == 0 {loadContacts()DispatchQueue.main.async {searchBar.resignFirstResponder()}}}}

Details List

After creating a new contact, we can see the details by pressing the its cell, and it would lead us to another View Controller.

After pressing “Edit” button, we can edit the contact’s details and then press the “Done” button to update to CoreData.

var editStatus: Bool = false//MARK: - Edit Button@IBAction func editButtonPressed(_ sender: UIBarButtonItem) {editStatus = !editStatussender.title = (editStatus) ? "Done" : "Edit"companyTextField.isUserInteractionEnabled = truemobileTextField.isUserInteractionEnabled = trueselectedContact?.mobile = mobileTextField.textselectedContact?.company = companyTextField.textupdateDetails()}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store