Screenshot of Safari from Share Extension

Can I take a screenshot of the current webview visible area in Safari from the Share extension? I could use windows, but UIApplication is not supported in extensions, so I cannot access this window.

+6
source share
4 answers

You cannot, because UIApplication cannot be reached from the extension. You cannot get the first UIWindow, which is a Safari layer, so you need to play with the Javascript preprocess file that the extensions have. So just create a Javascript file that when sent to Safari generates a base64 string with the current image data of the visible area. Take this line through the identifier kUTTypePropertyList in your extension. Since this should be NSData, generate a UIImage from there using +imageWithData . This is what you are looking for, without having to load the page again, preventing second loading and poor image if the web page requires login.

+2
source

As far as I know, you cannot, unless you call the API that you need dynamically, and even so you may run into context resolution problems and application store approval problems.

An alternative would be to pass the current Safari URL to your extension, load it using a hidden UIWebView and display this view in UIImage, but you will lose the current information about the visible zone ...

0
source

Edit: Thus, the following works in the simulator, but does not work on the device. I'm currently looking for a solution.

You cannot get only the visible area of ​​Safari, but you can get a screenshot with a little ingenuity. The following method displays a screenshot from ShareViewController.

 func captureScreen() -> UIImage { // Get the "screenshot" view. let view = UIScreen.mainScreen().snapshotViewAfterScreenUpdates(false) // Add the screenshot view as a subview of the ShareViewController 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 } 
0
source

This is an approved way to capture a screenshot of a webpage in a shared extension:

 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. }]; } } 
0
source

Source: https://habr.com/ru/post/974498/


All Articles