How to Get the title in share extension view controller?

我只是一个虾纸丫 提交于 2019-12-04 19:43:01
William Ku

You can use the ExtensionPreprocessingJS to do this.

First, add the the NSExtensionJavaScriptPreprocessingFile key to the NSExtensionAttributes dictionary in your Info.plist. The value should be the name of your JavaScript file without the extension, i.e. MyExtensionJavaScriptClass.

Then, in the NSExtensionActivationRule dictionary in your Info.plist, set the NSExtensionActivationSupportsWebPageWithMaxCount key with a value of 1 (type Number).

Next, add MyExtensionJavaScriptClass.js to your extension with the following code:

var MyExtensionJavaScriptClass = function() {};

MyExtensionJavaScriptClass.prototype = {
    run: function(arguments) {
       arguments.completionFunction({"title": document.title});
    } 
};

// The JavaScript file must contain a global object named "ExtensionPreprocessingJS".
var ExtensionPreprocessingJS = new MyExtensionJavaScriptClass;

Then include the following function in your ShareViewController viewDidLoad and import MobileCoreServices

    let extensionItem = extensionContext?.inputItems.first as! NSExtensionItem
    let itemProvider = extensionItem.attachments?.first as! NSItemProvider

    let propertyList = String(kUTTypePropertyList)
    if itemProvider.hasItemConformingToTypeIdentifier(propertyList) {
        itemProvider.loadItemForTypeIdentifier(propertyList, options: nil, completionHandler: { (item, error) -> Void in
            let dictionary = item as! NSDictionary
            NSOperationQueue.mainQueue().addOperationWithBlock {
                let results = dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as! NSDictionary
                let title = results["title"] as! String                                        
                //yay, you got the title now
            }
        })
    } else {
        print("error")
    }

I guess you've to request the site using the provided URL, parse the content and get the title from that string.

BTW: Apple Documentation say:

If your Share or iOS Action extension needs to access a webpage, you must include the NSExtensionActivationSupportsWebPageWithMaxCount key with a nonzero value

See the section "Accessing a Webpage"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!