Swift 4 vCard on touch添加到联系人

时间:2018-07-23 16:34:22

标签: swift vcard cncontact

我搜寻了互联网,希望找到一种保存人员联系信息的方法。当前,在我的移动网站上,我有一个vCard,当单击电话时,该vCard询问用户是否要将联系人添加到其联系人中。但是,迅速加载相同的链接会生成404错误页面。那我该怎么做呢?我想要当用户单击图标时弹出窗口显示,询问用户是否要将联系人保存到手机中。数据通过JSON API获取。我假设我需要获取此数据并以特定方式对其进行格式化。对此提出的任何建议或指示,将不胜感激。

谢谢

更新:这是我为此尝试的一些代码。当这打印到控制台时,我得到vcard输出,但是在JSONSerialization上引发了一个错误。也许有人可以指出我正确的方向。

@IBAction func contactTapped(_ sender: Any) {
    let contact = createContact()
    do {
        try shareContacts(contacts: [contact])
    } catch {
        print("Error printing contact")
    }
}

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)
    .appendingPathComponent("vcf")

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

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

    try JSONSerialization.data(withJSONObject: JSONEncoder(), options: JSONSerialization.WritingOptions.prettyPrinted)

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

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

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 = fullNameLbl.text!
    //contact.familyName = "Appleseed"

    let workEmail = CNLabeledValue(label:CNLabelWork, value: emailLbl.text! as NSString)
    contact.emailAddresses = [workEmail]

    contact.phoneNumbers = [CNLabeledValue(
        label:CNLabelPhoneNumberiPhone,
        value:CNPhoneNumber(stringValue: phoneLabel.text!))]

    let store = CNContactStore()
    let saveRequest = CNSaveRequest()
    saveRequest.add(contact, toContainerWithIdentifier: nil)
    try! store.execute(saveRequest)

    return contact
}

0 个答案:

没有答案