【问题标题】:macOS: SwiftUI: MenuItem for taking a screenshot of WKWebView and save it to ~/Pictures with a timestamp?macOS:SwiftUI:MenuItem 用于截取 WKWebView 的屏幕截图并将其保存到带有时间戳的 ~/Pictures?
【发布时间】:2020-01-20 13:05:32
【问题描述】:

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

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

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

虽然“MenuItem” -> 绑定到 -> First Responder -> @IBAction 是我现在熟悉的东西,但我不完全确定如何调用 WKWebView 快照以及如何定义它的时间戳名字。

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

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

【问题讨论】:

    标签: xcode macos swiftui wkwebview


    【解决方案1】:

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

    然后您可以使用saveImage - which is linked in the handy function at this answer 保存它。

    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)
                    }
                }
            }
    

    【讨论】:

    • 嗨,我在@IBAction 上方添加了public let webView: WKWebView = WKWebView(),因此webView 错误停止发生。但是,这并没有改变这些错误:“使用未解析的标识符'saveImage'”、@IBAction methods must have 1 argument 和“预期的';'分隔符”和“预期类型”。
    • 在从链接添加 saveImage 并将每个 UIImage 修改为 NSImage 之后,我仍然看到来自 saveImage 的Value of 'NSImage' has no member 'jpegData',以及实际的 ibaction 拍摄 Missing argument labels 'imageName:image:' in call@IBAction methods must have 1 argument 和 @ 987654331@ 在 ibaction 线下​​方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 2010-09-08
    • 1970-01-01
    • 2019-09-16
    • 2014-08-17
    • 1970-01-01
    相关资源
    最近更新 更多