如何创建要在共享表中使用的vCard / vcf文件?

时间:2016-07-12 17:31:57

标签: ios swift addressbook abaddressbook

我是swift的新手,我发现的方法因我的问题而被弃用。我正在构建一个目录应用,并且我从API中提取联系人数据,而不是从手机的地址簿中提取。

在iOS中,如果您转到地址簿,则可以选择联系人并选择“共享联系人”。这会带来一份分享表。我想在我的应用程序中使用这个功能。

我已经找到了Share Table,并且这是我的代码:

    @IBAction func actShare(sender: AnyObject) {

    let activityViewController = UIActivityViewController(activityItems: ["text" as NSString], applicationActivities: nil)
    presentViewController(activityViewController, animated: true, completion: {})
}

我想将"text" as NSString更改为vCard,因为这是iOS从地址簿中分享的对象,对吧?假设我是对的,我想从我自己的应用程序的联系对象创建一个vCard,以便将其分享给相应的应用程序(电子邮件,短信等)。

我如何在Swift中实现这一目标?如果我错了,请纠正我并告诉我我需要做什么。感谢。

编辑:好的,这是我的变化。

@IBAction func actShare(sender: AnyObject) {
    do {
        var contactData = NSData()
        try contactData = CNContactVCardSerialization.dataWithContacts([createContact()])

        let activityViewController = UIActivityViewController(activityItems: [contactData as NSData], applicationActivities: nil)
        presentViewController(activityViewController, animated: true, completion: {})
    } catch {
        print("CNContactVCardSerialization cannot save address")
    }

func createContact() -> CNMutableContact {
    let contactCard = CNMutableContact()
    contactCard.givenName = "John"
    contactCard.familyName = "Doe"
    contactCard.emailAddresses = [
        CNLabeledValue(label: CNLabelWork, value: "john.doe@email.com")
    ]

    return contactCard
}

但是,当我点击共享按钮并显示我的共享表时,我选择了我要共享的应用程序,并且它没有按预期添加/附加联系人数据。我该如何做到这一点?

5 个答案:

答案 0 :(得分:9)

这里的技巧是使用CNContactVCardSerialization.dataWithContacts将联系人保存到VCard(.vcf)文件,然后将文件URL传递给UIActivityViewController。活动视图控制器从文件扩展名中检测VCard格式,并显示支持该格式的应用程序(例如,消息,邮件,便笺,Airdrop等)

示例:

@IBAction func buttonTapped(button: UIButton) {

    let contact = createContact()

    do {
        try shareContacts([contact])
    }
    catch {
        // Handle error
    }
}

func shareContacts(contacts: [CNContact]) throws {

    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 = try CNContactVCardSerialization.dataWithContacts(contacts)

    print("filename: \(filename)")
    print("contact: \(String(data: data, encoding: NSUTF8StringEncoding))")

    try data.writeToURL(fileURL, options: [.AtomicWrite])

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

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

func createContact() -> CNContact {

    // 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"))]

    return contact
}

Activity view controller showing apps which support VCard format

VCard contact appearing in Messages app

答案 1 :(得分:3)

您可以使用CNContact(需要iOS 9):

let contact = CNMutableContact()
    contact.givenName = "John"
    contact.familyName = "Doe"
    contact.emailAddresses = [
      CNLabeledValue(label: CNLabelWork, value: "john.doe@email.com")
    ]

答案 2 :(得分:2)

  

从iOS应用创建联系人并分享是非常简单的   外部应用程序。

首先,您需要创建分享按钮操作,如下所示: -

-(void)shareContactAction:(UIButton*)sender
{  
    CNMutableContact *selectedCon = [[CNMutableContact alloc] init];
    selectedCon.givenName = @"ABC";
    selectedCon.familyName = @"XYZ";
    NSString *phoneNum = @"+91-XXXXXXXXXXX"
    CNLabeledValue *contactNum1 = [CNLabeledValue labeledValueWithLabel:CNLabelHome value:[CNPhoneNumber phoneNumberWithStringValue:phoneNum]];
    selectedCon.phoneNumbers = @[contactNum1];
    NSString *url=[self saveContactDetailsToDocDir:selectedCon];
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[@"Contact", [NSURL fileURLWithPath:url]] applicationActivities:nil];
    [self presentViewController:activityViewController animated:YES completion:nil];     
}
  

你可以调用下面的函数来返回路径   上面按钮事件中的联系卡。

- (NSString *)saveContactDetailsToDocDir:(CNContact *)contact {

    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * contactCardPath = [documentsDirectory stringByAppendingString:@"/vCardName.vcf"];
    NSArray *array = [[NSArray alloc] initWithObjects:contact, nil];
    NSError *error;
    NSData *data = [CNContactVCardSerialization dataWithContacts:array error:&error];
    [data writeToFile:contactCardPath atomically:YES];

    return contactCardPath;
}

答案 3 :(得分:0)

已针对Swift 4更新:

@IBAction func buttonTapped(button: UIButton) {

    let contact = createContact()

    do {
        try shareContacts(contacts: [contact])
    }
    catch {
    // Handle error
    }
}

func shareContacts(contacts: [CNContact]) throws {

    guard let directoryURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
    return
    }

    var filename = NSUUID().uuidString

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

    if let fullname = CNContactFormatter().string(from: contact) {
        filename = fullname.components(separatedBy: " ").joined(separator: "")
    }
    }

    let fileURL = directoryURL
    .appendingPathComponent(filename)
    .appendingPathExtension("vcf")

    let data = try CNContactVCardSerialization.data(with: contacts)

    print("filename: \(filename)")
    print("contact: \(String(describing: String(data: data, encoding: String.Encoding.utf8)))")

    try data.write(to: fileURL, options: [.atomicWrite])

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

    present(activityController, animated: true, completion: nil)
}

func createContact() -> CNContact {

    // Creating a mutable object to add to the contact
    let contact = CNMutableContact()

    contact.imageData = NSData() as Data // 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"))]

    return contact
}

答案 4 :(得分:0)

成功的方法:

首先获取所有联系人,然后保存它,然后制作.vcf文件,并在电子邮件,WhatsApp,消息,Skype中共享.vcf并保存在iPhone文件中...。

enter image description here

@IBAction func vcfPressed(_ sender: UIButton) {

    let arrayContacts = self.fetchAllContacts()
    self.saveContactsInDocument(contacts: arrayContacts)
     let contact = fetchAllContacts()
     do {
     try shareContacts(contacts: contact)
     }
     catch {
     }
}


func shareContacts(contacts: [CNContact]) throws {

    guard let directoryURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
 return}

    var filename = NSUUID().uuidString
    if let contact = contacts.first, contacts.count == 1 {
    if let fullname = CNContactFormatter().string(from: contact) {
    filename = fullname.components(separatedBy: " ").joined(separator: "")}}
    let fileURL = directoryURL.appendingPathComponent(filename).appendingPathExtension("vcf")
    let data = try CNContactVCardSerialization.data(with: contacts)
    print("filename: \(filename)")
    print("contact: \(String(data: data, encoding: String.Encoding.utf8))")
    try data.write(to: fileURL, options: [.atomicWrite])
    let activityViewController = UIActivityViewController(activityItems: [fileURL],applicationActivities: nil)
    present(activityViewController, animated: true, completion: {})
 }


func fetchAllContacts() -> [CNContact] {

    var contacts : [CNContact] = []
    let contactStore = CNContactStore()
    let fetchReq = CNContactFetchRequest.init(keysToFetch: [CNContactVCardSerialization.descriptorForRequiredKeys()])
    do {
        try contactStore.enumerateContacts(with: fetchReq) { (contact, end) in
            contacts.append(contact)
        }}
    catch  {print("Failed to fetch")}
    return contacts
}

enter image description here