Search code examples
iosobjective-cswiftvcf-vcardcncontact

Contact image doesn't send when contact saved by CNContact


I've written a code that saves a contact with image. I used CNContact class to do it. It saves the contact successfully.

The contact shows correctly with thumbnail in iOS's default Contact app. But my problem is that, when I share that contact via SMS or Email using iOS's default Contact app, the image doesn't add up in vCard.

Can anybody guide to me to what I've done wrong?

The following is the method that I used to save contact. It is in Swift.

func addContact(withData: ContactModel, andPicture picture: NSData?) -> Bool {
    if(checkForPermission() != true) {
        print("No permission")
        return false
    }

    let contact = convertToCNMutableContact(withData)
    contact.imageData = picture
    let saveRequest = CNSaveRequest()
    saveRequest.addContact(contact, toContainerWithIdentifier: nil)
    do {
        try contactStore.executeSaveRequest(saveRequest)
        return true
    } catch  {
        print("Couldn't save contact")
        return false
    }
}

Solution

  • I figured out the problem. When I use CNContactVCardSerialization.dataWithContacts(), I get the image as NSData. If I convert it as UIImageJPEGRepresentation/UIImageJPEGRepresentation and then append the image with the vCard string as @"PHOTO;BASE64;ENCODING=b;TYPE=JPEG%@" and then append the image data, then picture is sent with vCard.