簡體   English   中英

ios:我想創建包含所有聯系人的.vcf / vcard。 我該怎么做呢?

[英]ios: I want to create .vcf/vcard which contains all my contacts. How do I do this?

我想創建一個.vcf文件與我創建的類似Android應用程序共享。 我可以為單個聯系人創建一個.vcf文件,但無法以相同方式為多個聯系人創建一個。 我已參考此鏈接以幫助創建單個聯系人的vcf文件。

創建一個vcf文件以與其他應用共享

我想用我的所有聯系人創建一個vcf文件。 我該怎么做?

PS-我正在開發Swift 2.0。

謝謝

我終於找到了一種方法。

func createContact() -> [CNContact] {

    let contactStore = CNContactStore()
    var contacts = [CNContact]()

    let fetchRequest = CNContactFetchRequest(keysToFetch:[CNContactVCardSerialization.descriptorForRequiredKeys()])

    do {
        try contactStore.enumerateContactsWithFetchRequest(fetchRequest) {
            (contact123, stop) in
            // Array containing all unified contacts from everywhere
            contacts.append(contact123)}
    }
    catch {
        print("unable to fetch contacts")
    }

    return contacts

}

上面的代碼將創建一個包含所有詳細信息的所有聯系人的列表。 您還可以僅選擇要從所有聯系人中獲取的密鑰(這可以作為搜索的過濾器)。

然后,只需使用CNContactVCardSerialization創建一個.vcard文件

func shareContacts(聯系人:[CNContact])拋出{

    guard let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first else {
        return
    }

    var filename = NSUUID().UUIDString

    // Create a human friendly file name if sharing a single contact.
    if let contact = contacts.first where contacts.count == 1 {

        if let fullname = CNContactFormatter().stringFromContact(contact) {
            filename = fullname.componentsSeparatedByString(" ").joinWithSeparator("")
        }
    }

    let fileURL = directoryURL
        .URLByAppendingPathComponent(filename)
        .URLByAppendingPathExtension("vcf")

    let data: NSData?
    do {
        data = try CNContactVCardSerialization.dataWithContacts(contacts)
        print("filename: \(filename)")
        print("contact: \(String(data: data!, encoding: NSUTF8StringEncoding))")

        do {
            try data!.writeToURL(fileURL, options: [.AtomicWrite])
        }
        catch {
            print("eeror\(error)")
        }
    }
    catch {
        print("error\(error)")
    }

    let activityViewController = UIActivityViewController(
        activityItems: [fileURL],
        applicationActivities: nil
    )

    presentViewController(activityViewController, animated: true, completion: {})
}

上面的代碼將為您提供一個通過郵件,whatsapp等共享它的選項。

希望這對某人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM