在Safari中获取所选文本并在操作扩展中使用它

Rag*_*tto 9 xcode action mobile-safari ios8 ios-app-extension

我正在为Safari进行动作扩展,我需要在扩展中获取所选文本.

通常在iOS中,我使用此代码在webview中获取所选文本

selectedText.text = [WebView stringByEvaluatingJavaScriptFromString: @ "window.getSelection (). toString ()"];
Run Code Online (Sandbox Code Playgroud)

但在扩展内部我不知道该怎么办!

为了完整性,它应该是IU的扩展,我只是打开NSExtensionActivationSupportsWebURLWithMaxCount以在Safari中提供扩展.

提前致谢

Tom*_*ton 10

正如Apple在他们的App Extension编程指南中解释的那样,您需要在扩展中包含一个JavaScript文件来执行任何预处理.预处理的结果可通过NSExtensionItem扩展中获得.

这个文件的一个简单示例包含在GitHub的iOS Extension Demo项目中,如下所示:

var MyPreprocessor = function() {};

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

var ExtensionPreprocessingJS = new MyPreprocessor;
Run Code Online (Sandbox Code Playgroud)

这只是提取有关当前页面的各种细节并将它们传递给completionFunction.最后的ExtensionPreprocessingJSvar是扩展框架寻找的钩子.

在扩展中,您可以通过询问类型的项来在字典中检索这些值kUTTypePropertyList:

for (NSExtensionItem *item in self.extensionContext.inputItems) {
    for (NSItemProvider *itemProvider in item.attachments) {
        if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypePropertyList]) {
            [itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypePropertyList options:nil completionHandler:^(NSDictionary *jsDict, NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSDictionary *jsPreprocessingResults = jsDict[NSExtensionJavaScriptPreprocessingResultsKey];
                    // Continue with data returned from JS...
Run Code Online (Sandbox Code Playgroud)