【问题标题】:Export iPhone contacts to .vcf file programmatically以编程方式将 iPhone 联系人导出到 .vcf 文件
【发布时间】:2016-11-13 11:44:12
【问题描述】:
我想在联系人应用程序中选择 iPhone 联系人,生成 .vcf 文件,将选择的联系人写入此文件并发送到服务器。
据我所知,在 iOS 9 中,通讯录的许多功能都被贬低了,所以任何人都可以帮助我以正确的方式编写这段代码。
【问题讨论】:
标签:
ios
swift
ios9
abaddressbook
vcf-vcard
【解决方案1】:
您需要的一般部件是:
- 用于访问手机联系人的Contacts 框架。
-
ContactsUI 框架使用内置视图控制器来访问联系人。
- 使用CNContactVCardSerialization.dataWithContacts 将
CNContact 数据编码为VCard 格式。
- 使用data.writeToURL将数据写入文件。
- 使用NSURLSession将数据上传到服务器。
以下示例回答了将联系人保存为 VCard 格式的问题。
import Contacts
// Creating a mutable object to add to the contact
let contact = CNMutableContact()
contact.imageData = NSData() // The profile picture as a NSData object
contact.givenName = "John"
contact.familyName = "Appleseed"
let homeEmail = CNLabeledValue(label:CNLabelHome, value:"john@example.com")
let workEmail = CNLabeledValue(label:CNLabelWork, value:"j.appleseed@icloud.com")
contact.emailAddresses = [homeEmail, workEmail]
contact.phoneNumbers = [CNLabeledValue(
label:CNLabelPhoneNumberiPhone,
value:CNPhoneNumber(stringValue:"(408) 555-0126"))]
let homeAddress = CNMutablePostalAddress()
homeAddress.street = "1 Infinite Loop"
homeAddress.city = "Cupertino"
homeAddress.state = "CA"
homeAddress.postalCode = "95014"
contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]
let birthday = NSDateComponents()
birthday.day = 1
birthday.month = 4
birthday.year = 1988 // You can omit the year value for a yearless birthday
contact.birthday = birthday
let data = try CNContactVCardSerialization.dataWithContacts([contact])
let s = String(data: data, encoding: NSUTF8StringEncoding)
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first {
let fileURL = directoryURL.URLByAppendingPathComponent("john.appleseed").URLByAppendingPathExtension("vcf")
try data.writeToURL(fileURL, options: [.AtomicWrite])
}