What I want
I'm trying to achieve the following user flow:
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?
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