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.
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.
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.
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)
}
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:"demoxyz@gmail.com" 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With