Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 722
Salome Tsiramua Avatar asked Jul 11 '16 13:07

Salome Tsiramua


1 Answers

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:"[email protected]")
let workEmail = CNLabeledValue(label:CNLabelWork, value:"[email protected]")
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])
}
like image 85
Luke Van In Avatar answered Nov 07 '22 16:11

Luke Van In