I have contact data in my iOS app. I’ve created a CNMutableContact object and populated it with this data. Next, I created an NSItemProvider with this data and used it to create a UIDragItem. However, when I drag the contact view and drop it onto the Contacts app, the contact does not get imported. What could be the issue here?
UITableViewDragDelegate’s itemsForBeginning method.
First Attempt
func tableView(_ tableView: UITableView, itemsForBeginning session: any UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let contact = CNMutableContact()
contact.givenName = "FIRST_NAME_LABEL"
contact.middleName = "LAST_NAME_LABEL"
contact.namePrefix = "MR"
contact.note = "NoteContent"
let dragItemProvider = NSItemProvider(object: contact)
let dragItem = UIDragItem(itemProvider: dragItemProvider)
return [dragItem]
}
Second Attempt
func tableView(_ tableView: UITableView, itemsForBeginning session: any UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let contact = CNMutableContact()
contact.givenName = "FIRST_NAME_LABEL"
contact.middleName = "LAST_NAME_LABEL"
contact.namePrefix = "MR"
contact.note = "NoteContent"
let dragItemProvider = NSItemProvider()
dragItemProvider.registerDataRepresentation(forTypeIdentifier: UTType.vCard.identifier, visibility: .all) { completionHandler in
completionHandler(self.getVCardData(fromcontact: contact), nil)
return nil
}
let dragItem = UIDragItem(itemProvider: dragItemProvider)
return [dragItem]
}
func getVCardData(fromcontact contact: CNContact) -> Data? {
do {
return try CNContactVCardSerialization.data(with: [contact])
} catch {
print("Error converting contact to vCard: (error.localizedDescription)")
return nil
}
}