How to get VCF data with contact images using CNContactVCardSerialization dataWithContacts: method?

前端 未结 3 614
忘了有多久
忘了有多久 2020-12-19 06:25

I\'m using CNContacts and CNContactUI framework and picking a contact via this

CNContactPickerViewController *contactPicker = [CNContactPickerViewController          


        
3条回答
  •  醉酒成梦
    2020-12-19 07:00

    I'd like to improve upon and modernise for Swift 3 the excellent answer by kudinovdenis.

    Just put the following extension into your project

    import Foundation
    import Contacts
    
    extension CNContactVCardSerialization {
        internal class func vcardDataAppendingPhoto(vcard: Data, photoAsBase64String photo: String) -> Data? {
            let vcardAsString = String(data: vcard, encoding: .utf8)
            let vcardPhoto = "PHOTO;TYPE=JPEG;ENCODING=BASE64:".appending(photo)
            let vcardPhotoThenEnd = vcardPhoto.appending("\nEND:VCARD")
            if let vcardPhotoAppended = vcardAsString?.replacingOccurrences(of: "END:VCARD", with: vcardPhotoThenEnd) {
                return vcardPhotoAppended.data(using: .utf8)
            }
            return nil
    
        }
        class func data(jpegPhotoContacts: [CNContact]) throws -> Data {
            var overallData = Data()
            for contact in jpegPhotoContacts {
                let data = try CNContactVCardSerialization.data(with: [contact])
                if contact.imageDataAvailable {
                    if let base64imageString = contact.imageData?.base64EncodedString(),
                        let updatedData = vcardDataAppendingPhoto(vcard: data, photoAsBase64String: base64imageString) {
                        overallData.append(updatedData)
                    }
                } else {
                    overallData.append(data)
                }
            }
            return overallData
        }
    }
    

    and then you can use it similarly to the existing serialisation method:

    CNContactVCardSerialization.data(jpegPhotoContacts: [contact1, contact2])
    

    Note that this takes care of serialisation, you'll need to write a similar method for deserialisation if you are also importing.

提交回复
热议问题