以编程方式将iPhone联系人导出到.vcf文件

时间:2016-07-11 13:38:13

标签: ios swift ios9 abaddressbook vcf

我想在联系人应用程序中选择iPhone联系人,生成.vcf文件,在此文件中写入所选联系人并发送到服务器。

正如我在iOS 9中所知,地址簿的许多功能都被折旧了,所以任何人都可以帮助我以正确的方式编写这段代码。

1 个答案:

答案 0 :(得分:5)

您需要的一般部分是:

  1. Contacts访问手机联系人的框架。
  2. 使用内置视图控制器访问联系人的ContactsUI框架。
  3. 使用CNContactVCardSerialization.dataWithContactsCNContact数据编码为VCard格式。
  4. 使用data.writeToURL将数据写入文件。
  5. 使用NSURLSession将数据上传到服务器。
  6. 下面是一个回答将联系人保存为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])
    }