macOS: SwiftUI: 用于截取 WKWebView 屏幕截图并将其保存到带有时间戳的 ~/图片的菜单项?



我正在创建一个macOS SwiftUI应用程序,该应用程序可以打开WKWebView到特定的URL。

现在,我正在尝试将 MenuItem 映射到一个函数,该函数获取 WKWebView 窗口的屏幕截图,并将其保存到带有时间戳的 ~/Pictures。

我试图通过教程寻找这个,但只找到了iOS WKSnapShot类型的东西。

虽然"MenuItem"(>绑定到->第一响应者->@IBAction是我现在有点熟悉的东西,但我不完全确定如何调用WKWebView快照以及如何定义它的时间戳名称。

@IBAction func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration?,
completionHandler: @escaping (NSImage?, Error?) -> Void)
{
}

这开始向我射击错误:@IBAction methods must have 1 argument

您只需要在 webView 上调用快照函数。要使 webView 快照功能可用,您需要使其在AppDelegate.swift中可用

然后您可以使用saveImage保存它 - 它在此答案的方便功能中链接。

public let webView: WKWebView = WKWebView()
@IBAction func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration,
completionHandler: @escaping (NSImage *snapshotImage) -> Void)
{
self.webView.takeSnapshot(with: snapshotConfiguration) { image, error in
let formatter = DateFormatter()
formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
name = (formatter.string(from: Date()) as NSString) as String
if let image = image {
saveImage(name, image)
}
}
}

最新更新