1

I'm creating a macOS SwiftUI app that opens a WKWebView to a specific URL.

Now I'm attempting to make a MenuItem mapped to a function that takes a screenshot of the WKWebView window, and saves it to ~/Pictures with a timestamp.

I tried to look for this via tutorials but only found iOS WKSnapShot type stuff.

While the "MenuItem" -> bind to -> First Responder -> @IBAction is something I'm kind of familiar with now, I'm not entirely sure how to call the WKWebView snapshotting and how to define it's timestamped name.

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

This started shooting errors at me: @IBAction methods must have 1 argument

esaruoho
  • 896
  • 1
  • 7
  • 25

1 Answers1

0

You just need to call the snapshot function on the webView. To get the webView snapshot function to be available, you need to make it available in the AppDelegate.swift

Then you can save it by using 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)
                }
            }
        }
New Alexandria
  • 6,951
  • 4
  • 57
  • 77
  • 1
    Hi, I added `public let webView: WKWebView = WKWebView()` above the `@IBAction` so the webView error stopped occurring. However, that did not change these errors: "Use of unresolved identifier 'saveImage'", `@IBAction methods must have 1 argument` and "Expected ';' separator" and "Expected type". – esaruoho Jan 20 '20 at 19:17
  • after adding the saveImage from the linked link, and modifying each UIImage to NSImage, I'm still seeing `Value of 'NSImage' has no member 'jpegData'` from saveImage, and also the actual ibaction shoots `Missing argument labels 'imageName:image:' in call` and `@IBAction methods must have 1 argument` and `Expected type` below the ibaction line. – esaruoho Jan 20 '20 at 19:58