我注意到 WKWebView
文档现在列出了一个名为 takeSnapshot
的方法iOS 11 和 macOS 10.13 及更高版本 (Xcode 9 beta) 支持。
有没有人玩过或实现过?我试图让它在 Playground 上工作,但我不确定从哪里开始?这是 WKWebView
上的方法吗?
我的代码:
import UIKit
import PlaygroundSupport
import WebKit
let frame = CGRect(x: 0, y: 0, width: 800, height:600)
let web = WKWebView(frame: frame)
let rq = URLRequest(url: NSURL(string: "http://apple.com")! as URL)
web.load(rq)
PlaygroundPage.current.liveView = web
PlaygroundPage.current.needsIndefiniteExecution = true
//Take snapshot?
最佳答案
据我测试,takeSnapshot(with:completionHandler:)
方法实际上作为实例方法存在并且按预期工作。
就是有点难用。
该方法将其第一个参数声明为 WKSnapshotConfiguration?
,但类 WKSnapshotConfiguration
未使用 import WebKit
导入。您可以将 nil
传递给参数,但要使用该方法,您需要导入类型 WKSnapshotConfiguration
。而且我找不到任何依赖子模块来导入 WKSnapshotConfiguration
。
所以,如果你想玩这个新功能,你需要创建一个带有桥接头的应用程序项目。 (如果你知道如何在 Playground 中使用 bridging-header,你可以在其中测试这个功能。但我不知道你是否可以或如何。)
{ProjectName}-Bridging-Header.h:
@import CoreGraphics;
#import <WebKit/WKSnapshotConfiguration.h>
还有一个 ViewController.swift 的例子:
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let request = URLRequest(url: URL(string: "http://apple.com")!)
webView.load(request)
}
@IBAction func buttonPressed(_ sender: UIButton) {
webView.takeSnapshot(with: nil) {image, error in
if let image = image {
self.imageView.image = image
print("Got snapshot")
} else {
print("Failed taking snapshot: \(error?.localizedDescription ?? "--")")
}
}
}
}
(在 View 上放置一个 WKWebView
、一个 UIImageView
和一个 UIButton
。)
另外,这似乎是WebKit框架的一个bug,你最好发一个bug report给苹果。
关于ios - WKWebView(beta)的takeSnapshot方法,如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600451/