实现一个分享扩展插件,功能是从Safari网页中截取当前网页的图片内容
基本的步骤总结在下面:
1.创建一个JS文件,命名为MyJavascriptFile.js,文件的功能是解析safari网页内容,获取到网页中的所有图片节点,解析从图片的URL,返回所有图片URL拼接而成的字符串。
JS中主要用到run: function(arguments){}这个方法来处理抓取数据的逻辑,处理抓取到的数据调用 arguments.completionFunction({ "webImages": imageArrStr }); 这个方法把数据返回,"webImages"这个key可以自定义,在第三步的原生层OC代码中需要用到这个key把JS层抓取到的数据取出来,然后可以对这些图片数据进行保存、上传等需要的操作了。
MyJavascriptFile.js文件内容
var BuscapeClass = function() {};
BuscapeClass.prototype = {
run: function(arguments) {
var imageArray = new Array();
var objs = document.getElementsByTagName("img");
for(var i=0;i<objs.length;i++){
if(imageArray.indexOf(objs[i].src) == -1){
imageArray.push(objs[i].src);
}
}
var imageArrStr = imageArray.join('+');
// Pass the baseURI of the webpage to the extension.
arguments.completionFunction({ "webImages": imageArrStr });
},
// Note that the finalize function is only available in iOS.
finalize: function(arguments) {
// arguments contains the value the extension provides in [NSExtensionContext completeRequestReturningItems:completion:].
// In this example, the extension provides a color as a returning item.
// document.body.style.backgroundColor = arguments["bgColor"];
var bestOffer = arguments["bestOffer"];
alert("A melhor oferta é da loja\n" + bestOffer["sellername"] + " por " + bestOffer["price"]);
}
};
// The JavaScript file must contain a global object named "ExtensionPreprocessingJS".
var ExtensionPreprocessingJS = new BuscapeClass;
2.在info.plis文件中把创建的JS文件进行配置,配置如下:
配置的源码
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<key>NSExtensionActivationRule</key>
<string>SUBQUERY (
extensionItems,
$extensionItem,
SUBQUERY (
$extensionItem.attachments,
$attachment,
(
ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.url"
|| ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.image"
|| ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.plain-text"
)
).@count >= $extensionItem.attachments.@count
).@count >= 1</string>
<key>NSExtensionJavaScriptPreprocessingFile</key>
<string>MyJavascriptFile</string>
</dict>
<key>NSExtensionMainStoryboard</key>
<string>MainInterface</string>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.share-services</string>
</dict>
3.原生层OC代码中处理JS抓取的数据,主要用到这两句,把数据取出来"webImages"这个key要和JS中定义的KEY一致
NSDictionary *results = jsDict[NSExtensionJavaScriptPreprocessingResultsKey];
NSString* result = [results objectForKey:@"webImages"];
完整的处理代码
- (void)fetchDataFromWebContent {
__weak typeof(self) weakSelf = self;
//获取inputItems,在这里itemProvider是你要分享的图片
NSArray* extensionItems = self.extensionContext.inputItems;
for (NSExtensionItem *extensionItem in extensionItems) {
NSMutableArray* tmpTypeImageArr = [NSMutableArray array];
NSMutableArray* tmpTypePropertyListArr = [NSMutableArray array];
NSArray* attachments = extensionItem.attachments;
// 处理attachments
for (NSItemProvider *itemProvider in attachments) {
// 注入JS获取图片数据数据
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypePropertyList]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypePropertyList options:nil completionHandler:^(NSDictionary *jsDict, NSError *error) {
NSLog(@"jsDict: %@", jsDict);
dispatch_async(dispatch_get_main_queue(), ^{
// Get javascript result
NSDictionary *results = jsDict[NSExtensionJavaScriptPreprocessingResultsKey];
NSString* result = [results objectForKey:@"webImages"];
BMLog(@"=== webImages ===%@", result);
NSArray* tmpArr = [weakSelf handleImages:result];
if (tmpArr.count > 0) {
[tmpTypePropertyListArr addObjectsFromArray:tmpArr];
}
[weakSelf handleResult:tmpTypePropertyListArr];
});
}];
}
}
}
}
- (NSArray*)handleImages:(NSString*)imagesStr {
NSMutableArray* mUrlArray = [NSMutableArray arrayWithArray:[imagesStr componentsSeparatedByString:@"+"]];
NSMutableArray* tmpUrls = [NSMutableArray array];
for (int i = mUrlArray.count-1; i>=0; i--) {
NSString* url = mUrlArray[i];
// 过滤空的和jpg的图像
if (![url isEmptyOrWhitespace]) {
// 在这里处理图片的URL
}
}
NSLog(@"mUrlArray = %@ tmpUrls = %@", mUrlArray, tmpUrls);
return tmpUrls;
}
参考资料:
App Extension Programming Guide