我想在联系人应用程序中选择iPhone联系人,生成.vcf文件,在此文件中写入所选联系人并发送到服务器。
正如我在iOS 9中所知,地址簿的许多功能都被折旧了,所以任何人都可以帮助我以正确的方式编写这段代码。
答案 0 :(得分:5)
您需要的一般部分是:
CNContact
数据编码为VCard格式。下面是一个回答将联系人保存为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])
}