【发布时间】:2014-08-28 15:41:42
【问题描述】:
是否可以通过共享扩展对 Safari 中 web 视图的当前可见区域进行屏幕截图?我可以使用窗口,但扩展不支持 UIApplication,因此我无法访问该窗口。
【问题讨论】:
标签: ios xcode ios8 ios-app-extension
是否可以通过共享扩展对 Safari 中 web 视图的当前可见区域进行屏幕截图?我可以使用窗口,但扩展不支持 UIApplication,因此我无法访问该窗口。
【问题讨论】:
标签: ios xcode ios8 ios-app-extension
因为无法从扩展程序访问 UIApplication,所以您不能。您无法获得第一个 UIWindow,即 Safari 层,因此您必须使用扩展具有的 Javascript 预处理文件。因此,只需创建一个 Javascript 文件,该文件在发送到 Safari 时会生成一个带有当前可见区域图像数据的 base64 字符串。通过扩展中的 kUTTypePropertyList 标识符获取该字符串。因为那应该是 NSData,所以使用 +imageWithData 从那里生成 UIImage。这就是您要查找的内容,无需再次加载页面,如果网页需要登录,可以防止第二次加载和错误图像。
【讨论】:
据我所知,除非您动态调用所需的 API,否则您不能这样做,即使如此,您也可能会遇到上下文权限问题和应用商店批准问题。
另一种方法是将当前的 Safari URL 传递给您的扩展,使用隐藏的 UIWebView 加载它并将此视图呈现为 UIImage,但您将丢失当前可见区域信息...
【讨论】:
编辑:所以下面在模拟器中工作,但 not 在设备上工作。我目前也在寻找解决方案。
你不能只得到 Safari 的可见区域,但你可以得到一个小技巧的截图。以下方法从 ShareViewController 中截取屏幕截图。
func captureScreen() -> UIImage
{
// Get the "screenshot" view.
let view = UIScreen.mainScreen().snapshotViewAfterScreenUpdates(false)
// Add the screenshot view as a subview of the ShareViewController's view.
self.view.addSubview(view);
// Now screenshot *this* view.
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0);
self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Finally, remove the subview.
view.removeFromSuperview()
return image
}
【讨论】:
这是在共享扩展中捕获网页屏幕截图的认可方式:
for (NSExtensionItem *item in self.extensionContext.inputItems) {
for (NSItemProvider *itemProvider in item.attachments) {
[itemProvider loadPreviewImageWithOptions:@{NSItemProviderPreferredImageSizeKey: [NSValue valueWithCGSize:CGSizeMake(60.0f, 60.0f)]} completionHandler:^(UIImage * item, NSError * _Null_unspecified error) {
// Set the size to that desired, however,
// Note that the image 'item' returns will not necessarily by the size that you requested, so code should handle that case.
// Use the UIImage however you wish here.
}];
}
}
【讨论】: