iOS YouTube Share Extension Not Providing URL

Viewed 1946

I have the following code in my share extension to get the URL that is shared.

    if let item = extensionContext?.inputItems.first as? NSExtensionItem {
        for (index, _) in (item.attachments?.enumerated())! {
            if let itemProvider = item.attachments?[index] as? NSItemProvider {
                if itemProvider.hasItemConformingToTypeIdentifier("public.url") {
                    itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil, completionHandler: { (url, error) -> Void in
                        if let shareURL = url as? NSURL {
                            // send url to server to share the link
                            print (shareURL.absoluteString!)

For some reason the iOS YouTube app returns false for itemProvider.hasItemConformingToTypeIdentifier("public.url").

And below is my Info.plist for the share extension.

<key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>NSExtensionActivationRule</key>
        <string>
            SUBQUERY (
                extensionItems,
                $extensionItem,
                SUBQUERY (
                    $extensionItem.attachments,
                    $attachment,
                    ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.url"
                ).@count == 1
            ).@count == 1
        </string>
    </dict>
    <key>NSExtensionMainStoryboard</key>
    <string>MainInterface</string>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.share-services</string>
</dict>

How can I get the URL for the YouTube video shared in my share extension?

2 Answers

Youtube will provide a kUTTypePlainText. To obtain an URL you have to convert from NSSecureCoding to String and then build the URL with that string.

func getUrl() {
  if let content = extensionContext!.inputItems[0] as? NSExtensionItem {

    let contentTypePlain = kUTTypePlainText as String

    if let contents = content.attachments {
      for attachment in contents {
        if attachment.hasItemConformingToTypeIdentifier(contentTypePlain) {
          attachment.loadItem(forTypeIdentifier: contentTypePlain, options: nil, completionHandler: { data, error in
            let urlString = data as! String
            let url = URL(string: urlString)!

            // USE URL 

          })
        }
      }
    }
  }
} 
Related