通过 CNContact 从 iPhone 获取所有联系人列表时未获取联系人图像

Contact image not getting when fetch all contact list from iPhone by CNContact

我知道这个问题已经被问到但没有得到解决方案。

通过此代码,我将从联系人获取所有信息,但在 mac os 上打开 vcf 文件时找不到图像,共享此文件时也找不到图像。我使用这个 Whosebug link 但它没有帮助。

var contacts = [CNContact]()
let keys = [CNContactVCardSerialization.descriptorForRequiredKeys()
        ] as [Any]
let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])

    do {
        try self.contactStore.enumerateContacts(with: request) {
            (contact, stop) in
            // Array containing all unified contacts from everywhere
            contacts.append(contact)
        }
    } catch {
        print("unable to fetch contacts")
    }

    do {
        let data = try CNContactVCardSerialization.data(with: contacts)

        if let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let fileURL = directoryURL.appendingPathComponent("contacts").appendingPathExtension("vcf")
            print(fileURL)
            do {
                try data.write(to: fileURL, options: .atomic)
            } catch {
                print("error \(error)")
            }
        }

    } catch {
        print("error \(error)")
    }

可能,

let data = try CNContactVCardSerialization.data(with: contacts)

只添加联系信息,没有图片标签,因此您需要手动将图片标签添加到您的 VCF 文件中。你可以在这里找到解决方案。

是的, let data = try CNContactVCardSerialization.data(with: contacts) 仅提供联系人信息而不是图像数据,因此您需要这样做,您可以获得正确的 VCF 文件。

var finalData = Data()

    for contact in contacts {
        do {
            var data = try CNContactVCardSerialization.data(with: [contact])
            var vcString = String(data: data, encoding: String.Encoding.utf8)
            let base64Image = contact.imageData?.base64EncodedString()
            let vcardImageString = "PHOTO;TYPE=JPEG;ENCODING=BASE64:" + (base64Image ?? "") + ("\n")
            vcString = vcString?.replacingOccurrences(of: "END:VCARD", with: vcardImageString + ("END:VCARD"))
            data = (vcString?.data(using: .utf8))!
            finalData += data
        } catch {
            print("error \(error)")
        }
    }

    if let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        let fileURL = directoryURL.appendingPathComponent("contacts").appendingPathExtension("vcf")
        do {
            try finalData.write(to: fileURL, options: .atomic)
        } catch {
            print("error \(error)")
        }
    }