Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically add contact in Swift

I want to add a contact (just the name and phone number) programatically in Swift. I've found some Objective-C examples but I didn't get them to work, not even in Objective-C. I don't want this to involve AddressBookUI, because I want to get the values from my own UI.

like image 396
bjornorri Avatar asked Jun 26 '14 11:06

bjornorri


People also ask

How do I add contacts in Swift?

Add contact with a button click using swift 3emailAddresses = [workEmail] newContact. phoneNumbers = [CNLabeledValue( label:CNLabelPhoneNumberiPhone, value:CNPhoneNumber(stringValue:"0123456789"))] do { let saveRequest = CNSaveRequest() saveRequest. add(newContact, toContainerWithIdentifier: nil) try AppDelegate.

How do I find contacts in Swift?

Swift 4 and 5.import ContactsUI func phoneNumberWithContryCode() -> [String] { let contacts = PhoneContacts. getContacts() // here calling the getContacts methods var arrPhoneNumbers = [String]() for contact in contacts { for ContctNumVar: CNLabeledValue in contact. phoneNumbers { if let fulMobNumVar = ContctNumVar.


2 Answers

Swift 4 & 5

import ContactsUI

Inherit this class CNContactViewControllerDelegate

@IBOutlet var contactNameTxt: UITextField!
@IBOutlet var phoneNumberTxt: UITextField!

@IBAction func saveActionBtn(_ sender: UIButton) {

        let store = CNContactStore()
        let contact = CNMutableContact()

        // Name
        contact.givenName = contactNameTxt.text ?? ""

        // Phone
        contact.phoneNumbers.append(CNLabeledValue(
            label: "mobile", value: CNPhoneNumber(stringValue: phoneNumberTxt.text ?? "")))

        // Save
        let saveRequest = CNSaveRequest()
        saveRequest.add(contact, toContainerWithIdentifier: nil)
        try? store.execute(saveRequest)
}

enter image description here

like image 178
Akbar Khan Avatar answered Oct 03 '22 21:10

Akbar Khan


Add contact with a button click using swift 3

Add this row in project plist

Privacy - Contacts Usage Description

then

import AddressBook
import Contacts

On button click, you add the following

let newContact = CNMutableContact()
newContact.givenName = "Your Name"
newContact.jobTitle = "CTO xyz Company"

let workEmail = CNLabeledValue(label:CNLabelWork, value:"[email protected]" as NSString)
newContact.emailAddresses = [workEmail]
newContact.phoneNumbers = [CNLabeledValue(
    label:CNLabelPhoneNumberiPhone,
    value:CNPhoneNumber(stringValue:"0123456789"))]
do {
    let saveRequest = CNSaveRequest()
    saveRequest.add(newContact, toContainerWithIdentifier: nil)
    try AppDelegate.getAppDelegate().contactStore.execute(saveRequest)
} catch {
    AppDelegate.getAppDelegate().showMessage("Unable to save the new contact.")
}

On app delegate add some custom class

// MARK: Custom functions        
class func getAppDelegate() -> AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
}

func showMessage(_ message: String) {
    let alertController = UIAlertController(title: "Birthdays", message: message, preferredStyle: UIAlertControllerStyle.alert)

    let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action) -> Void in
    }

    alertController.addAction(dismissAction)

    let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
    let presentedViewController = pushedViewControllers[pushedViewControllers.count - 1]

    presentedViewController.present(alertController, animated: true, completion: nil)
}

func requestForAccess(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
    let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)

    switch authorizationStatus {
    case .authorized:
        completionHandler(true)

    case .denied, .notDetermined:
        self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
            if access {
                completionHandler(access)
            }
            else {
                if authorizationStatus == CNAuthorizationStatus.denied {
                    DispatchQueue.main.async(execute: { () -> Void in
                        let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
                        self.showMessage(message)
                    })
                }
            }
        })

    default:
        completionHandler(false)
    }
}

You are done; test the project and check the contact app.

like image 24
Abdul Karim Avatar answered Oct 03 '22 22:10

Abdul Karim