Contact image doesn't send when contact saved by CNContact

南楼画角 提交于 2019-12-13 14:27:25

问题


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
    }
}

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/38519255/contact-image-doesnt-send-when-contact-saved-by-cncontact

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!