1

I am trying to code a "webpage selector" on my app, using a fancy carousel to display the webpages thumbnails.

However, I don't want to display the webpages thumbnails as webViews on my carousel because I can get quite a large number (20-30) of webpages at the same time and loading all of those can cause a lot of lag.

So, I decided to use screenshots of the webpages and use those images to populate my carousel instead, making the carousel animation much smoother.

Here is my question: I would like to know if there is any way to take a screenshot of the webpage (without showing it on the app screen) and save the image into a list that I can use to populate the carousel.

I am aware of this question but is quite an old post, so I was wondering if there is another way to do it. Also, I tried to implement the suggested solution, but it did not work.

1 Answers1

0

You can create a WKWebView that is behind your view controller (and thus invisible) and constrained to the size that you want. Once the page finishes loading take a snapshot by using drawHierarchy(in:afterScreenUpdates:) inside of a UIGraphicsImageRender and save the resulting image as your thumbnail.

Josh Homann
  • 15,933
  • 3
  • 30
  • 33
  • Thank you! I trying to do that but all the screenshots are coming out black... I think this is due to the fact that when I am taking the screenshot the webpage is not yet loaded. – Paulo Rocha Mar 20 '19 at 14:47
  • set your webView.navigationDelegate and implement and wait for the `didFinish` method in WKNavigationDelegate https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455629-webview – Josh Homann Mar 20 '19 at 14:50