Amogh Shettigar
Amogh Shettigar

Reputation: 285

ios: I want to create .vcf/vcard which contains all my contacts. How do I do this?

I want to create a .vcf file to share with the similar Android application that I have created. I am able to create a .vcf file for a single contact but I am unable to do it for multiple contacts in the same way. I have referred to this link for help to create a vcf file for single contact.

Create a vcf file to share with different apps

I would like to create a vcf file with all my contacts. How do I do it?

P.S- I am working on swift 2.0.

Thanks

Upvotes: 1

Views: 1402

Answers (1)

Amogh Shettigar
Amogh Shettigar

Reputation: 285

I found a way to do this finally.

func createContact() -> [CNContact] {

    let contactStore = CNContactStore()
    var contacts = [CNContact]()

    let fetchRequest = CNContactFetchRequest(keysToFetch:[CNContactVCardSerialization.descriptorForRequiredKeys()])

    do {
        try contactStore.enumerateContactsWithFetchRequest(fetchRequest) {
            (contact123, stop) in
            // Array containing all unified contacts from everywhere
            contacts.append(contact123)}
    }
    catch {
        print("unable to fetch contacts")
    }

    return contacts

}

The above code will create a list of all your contacts which consists of all the details. You can also select only the keys you want to fetch from all the contacts(This may act as a filter for your search).

Then simply create a .vcard file using the CNContactVCardSerialization

func shareContacts(contacts: [CNContact]) throws {

    guard let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first else {
        return
    }

    var filename = NSUUID().UUIDString

    // Create a human friendly file name if sharing a single contact.
    if let contact = contacts.first where contacts.count == 1 {

        if let fullname = CNContactFormatter().stringFromContact(contact) {
            filename = fullname.componentsSeparatedByString(" ").joinWithSeparator("")
        }
    }

    let fileURL = directoryURL
        .URLByAppendingPathComponent(filename)
        .URLByAppendingPathExtension("vcf")

    let data: NSData?
    do {
        data = try CNContactVCardSerialization.dataWithContacts(contacts)
        print("filename: \(filename)")
        print("contact: \(String(data: data!, encoding: NSUTF8StringEncoding))")

        do {
            try data!.writeToURL(fileURL, options: [.AtomicWrite])
        }
        catch {
            print("eeror\(error)")
        }
    }
    catch {
        print("error\(error)")
    }

    let activityViewController = UIActivityViewController(
        activityItems: [fileURL],
        applicationActivities: nil
    )

    presentViewController(activityViewController, animated: true, completion: {})
}

The above code will give you an option to share it via Mail, whatsapp etc etc.

Hope this helps someone.

Upvotes: 2

Related Questions