Hi i am creating new contact using CNMutableContact() and adding few details as below.
let contact = CNMutableContact()
contact.givenName = “John”
let image = UIImage(named: "school")
let imgData = UIImagePNGRepresentation(image!)
contact.imageData = imgData
Using the fallowing function i am sharing the contact via Airdrop to any other device.
func shareContacts(contacts: [CNMutableContact]) 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: nil)
activityViewController.completionWithItemsHandler = { (activityType: UIActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) -> Void in
if completed == true {
print("Saved")
}
else
{
}
}
}
In the receiver device the contact is getting saved to the device contacts but the image is not saved. What wrong i am doing that is preventing the image to get saved?