iosswiftxcodeios8-share-extensionshare-extension

Share Selected Text - iOS Share Extension


I want to be able to share selected text, but my extension only appears when clicking on the share icon (and then it populates the field with the page title). I want my extension to appear when the user selects text and clicks "Share..." (like in picture below) and then I want it to populate the text area with the selected text.

I want extension to be accessible here

Share View Controller:

override func viewDidLoad() {
        super.viewDidLoad()

        customPopup()

        let extensionItem = extensionContext?.inputItems.first as! NSExtensionItem
        let itemProvider = extensionItem.attachments?.first as! NSItemProvider
        let propertyList = String(kUTTypePropertyList)
        if itemProvider.hasItemConformingToTypeIdentifier(propertyList) {
            itemProvider.loadItem(forTypeIdentifier: propertyList, options: nil, completionHandler: { (item, error) -> Void in
                guard let dictionary = item as? NSDictionary else { return }
                OperationQueue.main.addOperation {
                    if let results = dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary {
                            print("RESULTS: \n", results)
                    }
                }
            })
        } else {
            print("error")
        }
    }

Action.js (JS preprocessing)

var MyPreprocessor = function() {};

MyPreprocessor.prototype = {
run: function(arguments) {
    arguments.completionFunction({"URL": document.URL, "title": document.title, "selection": window.getSelection().toString()});
}
};

var ExtensionPreprocessingJS = new MyPreprocessor;

Info.plist


Solution

  • As it is right now, your NSExtensionActivationRule is explicitly asking for 1 web URL, so that is what you're getting.

    Instead, try changing your NSExtensionActivationRule (in info.plist) to:

    <dict>
        <key>NSExtensionActivationSupportsText</key>
        <true/>
    </dict>
    

    If that does not work, try the longer:

    <key>NSExtensionAttributes</key>
    <dict>
        <key>NSExtensionActivationUsesStrictMatching</key>
        <integer>2</integer>
        <key>NSExtensionActivationRule</key>
        <dict>
            <key>NSExtensionActivationDictionaryVersion</key>
            <integer>2</integer>
            <key>NSExtensionActivationSupportsText</key>
            <true/>
        </dict>
    </dict>
    

    You can read more in this post: IOS Share extension: how to read from notes posts.