Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 610
haider_kazal Avatar asked Mar 11 '23 15:03

haider_kazal


2 Answers

As @haider_kazal said, yes you can get contact image data into .vcf file as answered here [Example].

Sample :

As a workaround you can create PHOTO field inside of VCard.

NSError* error = nil;
NSData* vCardData = [CNContactVCardSerialization dataWithContacts:@[contact] error:&error];
NSString* vcString = [[NSString alloc] initWithData:vCardData encoding:NSUTF8StringEncoding];
NSString* base64Image = contact.imageData.base64Encoding;
NSString* vcardImageString = [[@"PHOTO;TYPE=JPEG;ENCODING=BASE64:" stringByAppendingString:base64Image] stringByAppendingString:@"\n"];
vcString = [vcString stringByReplacingOccurrencesOfString:@"END:VCARD" withString:[vcardImageString stringByAppendingString:@"END:VCARD"]];
vCardData = [vcString dataUsingEncoding:NSUTF8StringEncoding];

For some reasons CNContactVCardSerialization does not use any photo of contact. VCard after serialization is looks like:

BEGIN:VCARD
VERSION:3.0
PRODID:-//Apple Inc.//iPhone OS 9.3.2//EN
N:Contact;Test;;;
FN: Test  Contact 
END:VCARD

After insertion the PHOTO field inside VCard you will get

BEGIN:VCARD
VERSION:3.0
PRODID:-//Apple Inc.//iPhone OS 9.3.2//EN
N:Contact;Test;;;
FN: Test  Contact 
PHOTO;TYPE=JPEG;ENCODING=BASE64:<photo base64 string>
END:VCARD

After this insertion contact will looks fine in CNContactViewController

like image 99
Anand Kore Avatar answered Apr 26 '23 08:04

Anand Kore


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.

like image 30
haider_kazal Avatar answered Apr 26 '23 08:04

haider_kazal