Contact image not getting when fetch all contact list from iPhone by CNContact

362 Views Asked by At

I know this question already asked but not getting solution.

From this code I will get all the information from the contact but image not found when open vcf files on mac os, also not getting when share this file. I use this stackoverflow link here but It's not help full.

var contacts = [CNContact]()
let keys = [CNContactVCardSerialization.descriptorForRequiredKeys()
        ] as [Any]
let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])

    do {
        try self.contactStore.enumerateContacts(with: request) {
            (contact, stop) in
            // Array containing all unified contacts from everywhere
            contacts.append(contact)
        }
    } catch {
        print("unable to fetch contacts")
    }

    do {
        let data = try CNContactVCardSerialization.data(with: contacts)

        if let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let fileURL = directoryURL.appendingPathComponent("contacts").appendingPathExtension("vcf")
            print(fileURL)
            do {
                try data.write(to: fileURL, options: .atomic)
            } catch {
                print("error \(error)")
            }
        }

    } catch {
        print("error \(error)")
    }
2

There are 2 best solutions below

0
On

Probably,

let data = try CNContactVCardSerialization.data(with: contacts)

Only adds the contact info without image tag, and hence you need to add image tag manually into your VCF file. you can find the solution here.

https://stackoverflow.com/a/44308365/5576675

0
On

Yes, let data = try CNContactVCardSerialization.data(with: contacts) give only contacts info not image data so you need to do like this, you can get correct VCF files.

var finalData = Data()

    for contact in contacts {
        do {
            var data = try CNContactVCardSerialization.data(with: [contact])
            var vcString = String(data: data, encoding: String.Encoding.utf8)
            let base64Image = contact.imageData?.base64EncodedString()
            let vcardImageString = "PHOTO;TYPE=JPEG;ENCODING=BASE64:" + (base64Image ?? "") + ("\n")
            vcString = vcString?.replacingOccurrences(of: "END:VCARD", with: vcardImageString + ("END:VCARD"))
            data = (vcString?.data(using: .utf8))!
            finalData += data
        } catch {
            print("error \(error)")
        }
    }

    if let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        let fileURL = directoryURL.appendingPathComponent("contacts").appendingPathExtension("vcf")
        do {
            try finalData.write(to: fileURL, options: .atomic)
        } catch {
            print("error \(error)")
        }
    }