iOS Share Extension: get URL of page when sharing via context menu in Safari

sbichenko picture sbichenko · May 27, 2017 · Viewed 7.1k times · Source

What I want

I'm trying to achieve the following user flow:

  1. User is browsing a webpage in iOS Safari.
  2. User selects some content (text and images) and waits for context menu to appear.
  3. User selects the "Share..." item.
  4. User selects my App Extension in the sharing menu that comes up from the bottom.
  5. Selected content and the webpage URL is shared to a remote server via an HTT call.

What I tried

I made a Share extension via Xcode. Here's the NSExtension section of my info.plist:

<key>NSExtension</key>
<dict>
    <key>NSExtensionAttributes</key>
    <dict>
        <key>NSExtensionActivationRule</key>
        <dict>
            <key>NSExtensionActivationSupportsWebPageWithMaxCount</key>
            <integer>1</integer>
            <key>NSExtensionActivationSupportsText</key>
            <true/>
            <key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
            <integer>1</integer>
        </dict>
        <key>NSExtensionJavaScriptPreprocessingFile</key>
        <string>test</string>
    </dict>
    <key>NSExtensionMainStoryboard</key>
    <string>MainInterface</string>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.share-services</string>
</dict>

Here's the test.js file:

var GetURL = function() {};
GetURL.prototype = {
run: function(arguments) {
    arguments.completionFunction({"URL": document.URL});
}
};
var ExtensionPreprocessingJS = new GetURL;

I expected the following result: in viewDidLoad method extensionContext?.inputItems would provide me with several input items, through which I would be able to get the selected content and the web URL.

What goes wrong

In viewDidLoad method extensionContext?.inputItems provides me with only one item -- the plain text representation of the selected content (even when I selected images and text at the same time). I can live with plain text, but I need the webpage URL.

My question

How can I get URL of the opened webpage when using a Share extension to share selected content via context menu in iOS Safari?

Answer

Joe picture Joe · May 31, 2017

Swift 3

Try something along the lines of:

override func didSelectPost() {
    if let item = extensionContext?.inputItems.first as? NSExtensionItem,
        let itemProvider = item.attachments?.first as? NSItemProvider,
        itemProvider.hasItemConformingToTypeIdentifier("public.url") {
        itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil) { (url, error) in
            if let shareURL = url as? URL {
                // do what you want to do with shareURL
            }
            self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
    }
}

"public.url" can be replaced with the kUTTypeURL String imported from MobileCoreServices