Faruk
Faruk

Reputation: 2449

List of Contacts from Contacts App in SwiftUI

Hi I am trying to build an interface that lists all the contacts just like the Contacts and Phone app with the same UI. What I have tried so far is below. Basically I tried to implement CNContactPickerViewController from ContactsUI using the UIViewControllerRepresentable. However what I am getting is a blank white page.

struct ContactsViewController: UIViewControllerRepresentable {

    func makeUIViewController(context: UIViewControllerRepresentableContext<ContactsViewController>) -> CNContactPickerViewController {
        let controller = CNContactPickerViewController()
        controller.delegate = context.coordinator
        controller.displayedPropertyKeys = [CNContactGivenNameKey]
        return controller
    }

    func updateUIViewController(_ uiViewController: CNContactPickerViewController, context: UIViewControllerRepresentableContext<ContactsViewController>) {
        print("updating")
    }

    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }

    class Coordinator: NSObject, CNContactPickerDelegate {
        var parent: ContactsViewController

        init(_ contactsViewController: ContactsViewController) {
            self.parent = contactsViewController
        }

    }
}

And the SwiftUI file;

struct ContactsView: View {
    var body: some View {
        ContactsViewController()
    }
}

A reminder is I am calling the ContactsView inside of TabView in some other SwiftUI file. So I want show contacts in a SwiftUI View that is part of TabView. Any help would be really appreciated.

Upvotes: 5

Views: 3635

Answers (1)

Dave Largent
Dave Largent

Reputation: 27

There are two solutions here: https://stackoverflow.com/a/57621666/8818408

(1) works but flashes a view before showing the list of contacts. Not a good experience for the user.

(2) sort of works. It also flashes a view before showing the list of contacts. It shows with unexpected transparency and unexpected colors along leading, trailing, and bottom edges. These may be possible to sort out.

I'm just getting started trying to resolve issues with #2 above. If anyone can offer a solution that works completely, that would be great.Screen shot of #2

Upvotes: 1

Related Questions