Arjun Komath
Arjun Komath

Reputation: 2852

SwiftUI: Open CNContactViewController from NavigationView?

I'm trying to open CNContactViewController for creating a new contact from a NavigationView. So far this is what I've tried and failed:

  1. Added a navigation bar item and set the destination
        .navigationBarItems(trailing:
            NavigationLink(destination: self.addContact()) {
                Text("Add")
            }
        )
  1. addContact function returns the new view
    func addContact() -> CNContactViewController {
        let con = CNContact()
        let vc = CNContactViewController(forNewContact: con)
        return vc
    }

Unfortunately this doesn't seem to be working. I'm pretty new to iOS and SwiftUI and I'm not sure if this is the way to do it, any help would be appreciated!

Upvotes: 4

Views: 1475

Answers (2)

Bilal Şimşek
Bilal Şimşek

Reputation: 5943

complete solution ;

 .navigationBarItems(trailing:
            NavigationLink(destination: self.addContact()) {
                Text("Add")
            }
        )

function;

func addContact() -> MyCNContactViewController {
           let vc = MyCNContactViewController()
           return vc
       }

represantable struct to wrap `CNContactViewController``

struct MyCNContactViewController: UIViewControllerRepresentable {
    typealias UIViewControllerType = CNContactViewController
  
    func makeUIViewController(context: Context) -> CNContactViewController {
        
        let con = CNContact()
     
        let vc = CNContactViewController(forNewContact: con)
        
        vc.allowsActions = true
        
        return vc
    }

    func updateUIViewController(_ uiViewController: CNContactViewController, context: Context) {
        
    }
}

Upvotes: 0

meaning-matters
meaning-matters

Reputation: 22946

You must embed CNContactViewController in a UIViewControllerRepresentable.

Here's the Apple documentation.

And, here's a non-Apple article about it.

Because you're new to iOS, please be aware that SwiftUI is far from finished and fully documented. And that SwiftUI only runs on the newest iOS 13, so not all your potential app users may (already) have that iOS version installed.

Upvotes: 1

Related Questions