iosswiftios9abaddressbookvcf-vcard

Export iPhone contacts to .vcf file programmatically


I want to choose iPhone contacts in contacts application, generate .vcf file, write chosen contacts in this file and send to server.

As I know in iOS 9 many functions of address book are depreciated, so can anybody help me to write this code in a correct way.


Solution

  • The general pieces you will need are:

    1. The Contacts framework for accessing the phone's contacts.
    2. The ContactsUI framework to use the built-in view controllers for accessing contacts.
    3. Use CNContactVCardSerialization.dataWithContacts to encode CNContact data to VCard format.
    4. Write the data to a file using data.writeToURL.
    5. Upload the data to the server using NSURLSession.

    Below is an example which answers the question of saving a contact to VCard format.

    import Contacts
    
    // Creating a mutable object to add to the contact
    let contact = CNMutableContact()
    
    contact.imageData = NSData() // The profile picture as a NSData object
    
    contact.givenName = "John"
    contact.familyName = "Appleseed"
    
    let homeEmail = CNLabeledValue(label:CNLabelHome, value:"john@example.com")
    let workEmail = CNLabeledValue(label:CNLabelWork, value:"j.appleseed@icloud.com")
    contact.emailAddresses = [homeEmail, workEmail]
    
    contact.phoneNumbers = [CNLabeledValue(
        label:CNLabelPhoneNumberiPhone,
        value:CNPhoneNumber(stringValue:"(408) 555-0126"))]
    
    let homeAddress = CNMutablePostalAddress()
    homeAddress.street = "1 Infinite Loop"
    homeAddress.city = "Cupertino"
    homeAddress.state = "CA"
    homeAddress.postalCode = "95014"
    contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]
    
    let birthday = NSDateComponents()
    birthday.day = 1
    birthday.month = 4
    birthday.year = 1988  // You can omit the year value for a yearless birthday
    contact.birthday = birthday
    
    
    let data = try CNContactVCardSerialization.dataWithContacts([contact])
    
    let s = String(data: data, encoding: NSUTF8StringEncoding)
    
    if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first {
    
        let fileURL = directoryURL.URLByAppendingPathComponent("john.appleseed").URLByAppendingPathExtension("vcf")
    
        try data.writeToURL(fileURL, options: [.AtomicWrite])
    }