iosswiftios8-share-extension

How to create an iOS share extension for contacts


I am trying to create an iOS share extension to share contacts using the following code:

let contactType = "public.vcard"

override func viewDidLoad() {
    let items = extensionContext?.inputItems
    var itemProvider: NSItemProvider?

    if items != nil && items!.isEmpty == false {
        let item = items![0] as! NSExtensionItem
        if let attachments = item.attachments {
            if !attachments.isEmpty {
                itemProvider = attachments[0] as? NSItemProvider
            }
        }
    }

    if itemProvider?.hasItemConformingToTypeIdentifier(contactType) == true {
        itemProvider?.loadItemForTypeIdentifier(contactType, options: nil) { item, error in
            if error == nil { 
                print("item: \(item)")
            }
        }
    }
}

I am getting the following output:

item: Optional(<42454749 4e3a5643 4152440d 0a564552 53494f4e 3a332e30 0d0a5052 4f444944 3a2d2f2f 4170706c 6520496e 632e2f2f 6950686f 6e65204f 5320392e 322f2f45 4e0d0a4e 3a42656e 6e657474 3b436872 69733b3b 3b0d0a46 4e3a2043 68726973 20204265 6e6e6574 74200d0a 54454c3b 74797065 3d484f4d 453b7479 70653d56 4f494345 3b747970 653d7072 65663a28 36313529 c2a03432 352d3637 31390d0a 454e443a 56434152 440d0a>)

If i set a breakpoint I see that item has a type of NSSecureCoding. My question is how do I turn this into a CNContact?


Solution

  • The item you are getting is of type NSData. You have to transform it to String to get the vCard String:

    if itemProvider?.hasItemConformingToTypeIdentifier(contactType) == true {
        itemProvider?.loadItemForTypeIdentifier(contactType, options: nil) { item, error in
            if error == nil {
                if let data = item as? NSData, let vCardString = String(data: data, encoding: NSUTF8StringEncoding) {
                    print(vCardString)
                }
            }
        }
    }