我知道这个问题已经问了,但没有得到解决。
从此代码中,我将从联系人中获取所有信息,但在Mac OS上打开vcf文件时找不到该图像,而在共享此文件时也无法获取该图像。我使用了这个stackoverflow链接here,但并不能完全解决问题。
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)")
}
答案 0 :(得分:1)
是的,
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)")
}
}
答案 1 :(得分:0)
可能
let data = try CNContactVCardSerialization.data(with: contacts)
仅添加不带图像标签的联系人信息,因此您需要将图像标签手动添加到VCF文件中。您可以在此处找到解决方案。