I have scoured the internet looking to find a way to save a persons contact information. Currently on my mobile website I have a vCard that when clicked on a phone asks the user if they would like to add the contact to their contacts. In swift however loading that same link generates a 404 error page. So how would I go about doing this? I want when the user clicks on the icon a pop up displays asking the user if they want to save the contact to their phone. The data is being pulled in through a json api. I assume I need to take this data and format it in a specific way. Any suggestions or pointers in a direction to take this is much appreciated.
Thanks
Update: Here is my attempt at some code for this. When this prints to the console I get the vcard output, but an error is thrown on the JSONSerialization. Maybe someone can point me in the right direction.
@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
}