Hello fellow developers, I'm porting the screenshot logic for WKWebView at https://github.com/VernonVan/PPSnapshotKit/blob/master/PPSnapshotKit/Source/PPSnapshotHandler.m#L95 from Objective-C to Swift and faced a cryptic error.
FYI, Xcode 12.4 and Build version 12D4e.
let view = self.flutterWebView?.view()
let webView = self.flutterWebView!.webView;
let snapshotView = webView!.snapshotView(afterScreenUpdates: true);
webView!.superview!.addSubview(snapshotView!)
let currentOffset = webView!.scrollView.contentOffset
let currentFrame = webView!.frame
let currentSuperView = webView!.superview
var currentIndex = webView!.superview!.subviews.firstIndex(of: webView!)
let containerView = UIView(frame: webView!.bounds)
webView!.removeFromSuperview()
containerView.addSubview(webView!)
let totalSize = webView!.scrollView.contentSize
let page = ceil(totalSize.height / containerView.bounds.size.height)
webView!.scrollView.contentOffset = .zero;
webView!.frame = CGRect(0, 0, containerView.bounds.size.width, webView!.scrollView.contentSize.height);
UIGraphicsBeginImageContextWithOptions(totalSize, true, 0)
self.drawContentPage(targetView: containerView, webView: webView, index: 0, maxIndex: page) {
let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsGetImageFromCurrentImageContext()
webView?.removeFromSuperview()
currentSuperView?.insertSubview(webView, at: currentIndex)
webView?.frame = currentFrame
webView?.scrollView.contentOffset = currentOffset
snapshotView?.removeFromSuperview()
return result(snapshotImage?.pngData())
}
public func drawContentPage(targetView: UIView, webView: WKWebView, index: Int = 0, maxIndex: Int, completion: () -> Void) {
let splitFrame = CGRect.init(0, CGFloat(index) * targetView.bounds.height, targetView.bounds.size.width, targetView.frame.size.height)
var myFrame = webView.frame
myFrame.origin.y -= (CGFloat(index) * targetView.frame.size.height)
webView.frame = myFrame
DispatchQueue.main.asyncAfter(deadline: .now() + (DELAY_TIME_DRAW * Double(NSEC_PER_SEC))) {
targetView.drawHierarchy(in: splitFrame, afterScreenUpdates: true)
if (index < maxIndex) {
self.drawContentPage(targetView: targetView, webView: webView, maxIndex: maxIndex, completion: completion)
}
else {
completion()
}
}
}