Create Search Contacts App with SwiftUI

Tram Ho

Implementation plan

  • Use the Contacts framework to get phone contacts.
  • Put them on the SwiftUI List.
  • Use the UIViewRepresentable protocol to create UISearchBar for SwiftUI.
  • Filter contact list based on search text.

Get Started – Add Privacy Description

The Contacts framework allows you to retrieve contact information without making any changes.
To access that application, you first need to set privacy contacts using descriptions in the info.plist file.
Just add NSContactsUsageDescription with explanatory content.

Combining UISearchBar with UIViewRepresentable and Coordinators

Currently SwiftUI does not support integrated search bars.
Therefore, we need to conform our struct to the UIViewRepresentable protocol and initialize the UISearchBar of the UIKit in it as follows:

The makeCoordinator() function allows us to create a Coordinator class, which is responsible for communicating changes from UIKit View to the SwiftUI interface.
We will define the Coordinator class, and also declare the UISearchBarDelegate protocol:

Create ObservableObject class to get contacts

ObservableObject protocol is used to notify changes in SwiftUI view through the @Published property.

In the following code, we will retrieve the contacts, make sure permissions are granted and then store them in the @Published property:

SwiftUI needs a way to identify every single contact. To do that, we created an extension at the conform end with the Identifiable protocol.

Now all is set up to integrate the search bar.

Integrate SearchBarView

We use @EnvironmentObject to retrieve contacts.

In the following code, using the SwiftUI List, we can retrieve the contacts and filter them based on the values ​​entered in searchText .

Result:

Conclude

We have set up the SwiftUI contacts application with a fairly quick search function – although the search bar is not supported in SwiftUI.

Doing the same thing with the UITableView and the UISearchBar will be quite time-consuming, effort-intensive and code-intensive.

Hope to see SwiftUI 2.0 in WWDC 2020 supporting new features.

You can download the full source code from the Github Repository .

Thank you for watching here.

Source: medium.com

Share the news now

Source : Viblo