3

I'm trying to fill the information of a CNMutableContact to save it and share it, and everything works perfectly except the note (that should be a regular String) and the imageData.

This is what i'm trying to do:

let contact = CNMutableContact()
contact.note = "HELLO"

if let imageUrl = self.getImgLogo(), let url = URL(string: imageUrl) {
    contact.imageData = try? Data(contentsOf: url)
}

I set more things into the contact like the givenName, familyName, jobTitle, socialProfiles, phoneNumbers, emails, ... and everything works ok but those two things.

Anyone can tell me if am i doing something wrong?

Thanks!

1 Answer 1

3

I fixed the problem. The issue was related to the CNContactVCardSerialization that was ignoring the note and the imageData. So i made an extension to manage that problem:

import Contacts

extension CNContactVCardSerialization {
    
    
    class func dataWithExtraInformation(contacts: [CNContact]) throws -> Data {
        var text: String = ""
        for contact in contacts {
            let data = try CNContactVCardSerialization.data(with: [contact])
            var str = String(data: data, encoding: .utf8)!
            
            if let imageData = contact.imageData {
                let base64 = imageData.base64EncodedString()
                str = str.replacingOccurrences(of: "END:VCARD", with: "PHOTO;ENCODING=b;TYPE=JPEG:\(base64)\nEND:VCARD")
            }
            
            if !contact.note.isEmpty {
                str = str.replacingOccurrences(of: "END:VCARD", with: "NOTE:\(contact.note)\nEND:VCARD")
            }
            
            text = text.appending(str)
        }
        return text.data(using: .utf8)!
    }
}

It just gets the serialized card and adds the extra information that i needed ;)

Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.