Программное добавление контакта в Swift

Добавьте контакт нажатием кнопки с помощью Swift 3

Добавить эту строку в список iphone-app проекта

Конфиденциальность iphone-app - Описание использования ios-sdk контактов

затем

import AddressBook
import Contacts

При нажатии swift-language кнопки вы добавляете следующее

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.")
}

В abaddressbook делегате приложения добавьте ios-sdk настраиваемый класс

// 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)
    }
}

Готово; протестируйте iphone проект и проверьте приложение swift для контактов.

ios

iphone

swift

abaddressbook

2022-09-11T13:35:44+00:00