我做错了什么......?
在iOS上,我想要拍摄完整网页的快照。在iOS 11之前,如果没有处理大量逻辑来滚动WKWebView
' s scrollView
等,以前就不可能这样做。
向Webkit报告了以下错误并已修复:https://bugs.webkit.org/show_bug.cgi?id=161450
导致此更改:https://trac.webkit.org/changeset/212929/webkit
现在,我们在iOS 11上为我们提供了一个很好的API来拍摄WKWebView
内容的快照:https://developer.apple.com/documentation/webkit/wkwebview/2873260-takesnapshotwithconfiguration
这一切都非常棒,但是,在设备上使用此方法时,我无法获得快照。在模拟器中运行应用程序时,它的工作非常棒。
我在下面添加了两张图片进行比较。两者都是takeSnapshotWithConfiguration:completionHandler:
返回的图像,但大部分都是空白的。
我尝试过使用网络视图frame
,配置等,但没有运气。
我在想,也许模拟器链接到WebKit的macOS版本,不知何故它在那里工作正常。还有一个问题是WKSnapshotConfiguration
标题似乎也没有在Swift中公开,所以我不得不添加一个导入它的桥接标题。
这是一个针对任何好奇的人的示例项目:https://github.com/runmad/WebKitSnapshotTest
更新10/20:
所以这解决了它,但这是一个讨厌的黑客:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// webView.scrollView.contentSize == .zero initially, so put in a delay.
// It still may be .zero, though. In that case we'll just call the
// delegate method again.
let deadlineTime = DispatchTime.now() + .milliseconds(300)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
guard webView.scrollView.contentSize.height > 0 else {
self.webView(webView, didFinish: navigation)
return
}
// So this works... If you set the .frame of the webView
// to that of the just loaded .scrollView and then load the
// same URL again, the resulting .frame and .scrollView will
// be the same size and the image render on a device will be
// the correct size.
guard self.hasLoadedOnce else {
webView.frame = CGRect(x: self.view.bounds.width, y: 0, width: self.view.bounds.width, height: webView.scrollView.contentSize.height)
webView.load(URLRequest(url: URL(string: "https://www.apple.com")!))
self.hasLoadedOnce = true
return
}
webView.snapshotWebView(completionHandler: { (image, _) in
self.updateWith(image)
})
}
}
所以有几个问题:
(asyncAfter
我已经知道了这个并且已经在那里了)必须为快照添加延迟,因为scrollView
仍然可能是.zero
一点点
将WKWebView
的框架尺寸设置为正确scrollView
尺寸的框架尺寸无效
设置框架然后将WKWebView
重新加载到它的真实尺寸中
更新03/11:
我的雷达(35094298)今天被骗了33812691并关闭,这意味着苹果至少知道这个问题。
答案 0 :(得分:0)
FOR swift 3(完整的webview屏幕截图)
扩展名ScreenShortVC:UIWebViewDelegate {
func webViewDidFinishLoad(_ webView: UIWebView) {
if webView.isLoading == true {
// still loading
return
}else
{
let webViewFrame = FullScreenWebView.frame
let scrollViewOffset = FullScreenWebView.scrollView.contentOffset
if (FullScreenWebView.scrollView.contentSize.width == 0 || FullScreenWebView.scrollView.contentSize.height == 0)
{
print("nothing to take screenshot of")
}
FullScreenWebView.scrollView.setContentOffset(CGPoint(x: 0, y: -FullScreenWebView.scrollView.contentInset.top) , animated: false)
let screenRect = UIScreen.main.bounds
FullScreenWebView.frame = CGRect(x: webViewFrame.origin.x, y: webViewFrame.origin.y, width: screenRect.size.width, height: FullScreenWebView.scrollView.contentSize.height)
let cgSizeToUse = CGSize(width: screenRect.size.width , height: FullScreenWebView.scrollView.contentSize.height)
autoreleasepool{
UIGraphicsBeginImageContextWithOptions(cgSizeToUse, false, 0)
self.FullScreenWebView.layer.render(in: UIGraphicsGetCurrentContext()!)
let img = UIGraphicsGetImageFromCurrentImageContext()
let imageData = UIImageJPEGRepresentation(img!, 0.7)
let compressdImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressdImage!, nil, nil, nil)
print(imageData ?? "")
let currentFileName = "screenshot.jpeg"
let imageFilePath = fileDirectory[0].appending(currentFileName)
let imageFileURL = NSURL(fileURLWithPath: imageFilePath)
print(imageFileURL )
UIGraphicsEndImageContext()
}
FullScreenWebView.frame = webViewFrame
FullScreenWebView.scrollView.contentOffset = scrollViewOffset
}
print("finished")
// finish and do something here
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print("didFailLoadWithError \(error.localizedDescription)")
// error happens
}
}
答案 1 :(得分:0)
快捷键4
这对我有用(请注意:我使用了提供的示例项目中的扩展名)。
在webView(didFinish导航)内部,我使用JS查找内容的宽度和高度。然后,我设置了一个全局>>> template_d['a']['b']['c']
defaultdict(<function __main__.template_dict.<locals>.<lambda>()>,
{'a': defaultdict(...),
'b': defaultdict(...),
'c': defaultdict(...)})
变量,以便稍后在按下按钮时将其传递给rect
。设置约束后,以下代码中包含snapshot()
时,我无法工作。
snapshot()
对我来说,快照(snapshot())必须是一个新动作,在我的情况下,是单独按下按钮。我的结论是,需要设置约束并重新加载视图,以便正确调整内容的大小。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// To get the constraints properly set for preparation for the snapshot, the setup must be performed here.
self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
if complete != nil {
self.webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
guard let contentHeight = height as? CGFloat else { print("Content height could not be obtained"); return }
self.webView.evaluateJavaScript("document.body.scrollWidth", completionHandler: { (width, error) in
let contentWidth = width as! CGFloat
self.rect = CGRect(x: 0, y: 0, width: contentWidth, height: contentHeight)
self.heightConstraint.constant = contentHeight
// Because it is known that the web page has completely loaded, it is safe to enable a snapshot to be taken
self.takeSnapButton.isEnabled = true
})
})
}
})
}