Search code examples
xcodeswift3addressbook

Swift: How to redirect user to Add Contact screen with contact number


I have a mobile number on my view controller and using that mobile number I want to redirect the user to the Add Contact screen (Address Book).

Please note that I don't want to fill other fields (name, image and all) in background, just redirect the user to add a contact screen with a contact number where they can edit and save it accordingly.

Note: the problem is that I just started Swift and I'm actually from an Android background and I don't have an idea if there is any actions with intents just like this in Swift too.


Solution

  • Import the following

    import Contacts
    import ContactsUI
    

    Add CNContactViewControllerDelegate

    class ViewController: UIViewController, CNContactViewControllerDelegate
    

    And the following code

    let newContact = CNMutableContact()
    newContact.phoneNumbers.append(CNLabeledValue(label: "home", value: CNPhoneNumber(stringValue: "123456")))
    let contactVC = CNContactViewController(forUnknownContact: newContact)
    contactVC.contactStore = CNContactStore()
    contactVC.delegate = self
    contactVC.allowsActions = false
    let navigationController = UINavigationController(rootViewController: contactVC) //For presenting the vc you have to make it navigation controller otherwise it will not work, if you already have navigatiation controllerjust push it you dont have to make it a navigation controller
    self.present(navigationController, animated: true, completion: nil)