How do you obtain a contact within an action extension?

I've got an action extension which I'm invoking via the Phone app's call history share contact action.


My code is as follows:


for item in self.extensionContext!.inputItems as! [NSExtensionItem]

{

for provider in item.attachments! as! [NSItemProvider]

{

if provider.hasItemConformingToTypeIdentifier(kUTTypeContact as String)

{

provider.loadItem(forTypeIdentifier: kUTTypeContact as String, options: nil, completionHandler: { (contactCoder, error) in

OperationQueue.main.addOperation

{

if error == nil

{

if let contactCoder = contactCoder

{

if let theContact = CNContact(coder: contactCoder as! NSCoder)



The data type passed to the completion handler in the contactCoder parameter is NSSecureCoding, however XCode will not compile without casting it to an NSCoder on the last line, but when executed this results in a dynamic cast exception.



If kUTTypeContact is replaced with kUTTypeVCard then both hasItemConformingToTypeIdentifier and provider.loadItem will still execute, and I was thinking the type of data passed to the completion handler might change from an NSSecureCoding to an NSData, but it didn't and attempting to instantiate the CNContact still failed in the same way.


How can the CNContact be instantiated within the action extension?

Replies

Solved it


let theContacts = try CNContactVCardSerialization.contacts(with: contactCoder as! Data)