SwiftUI on macOS, app generating a png file on the desktop from a screenshot made to the pasteboard

Hi all,

I've written a macOS swiftUI app, which checks the availability of a website, i.e. to my cloud. In the case, the access is lost, I'm creating a screenshot to the pasteboard and I'm generating a POST request to a PHP script on my webserver, to send an information email to my email address.

I'm using the following 2 functions, to generate the screenshot and save it to the pasteboard. All based on the tutorial (very good!) from Grace Huang (https://www.youtube.com/watch?v=7nnYsRrtweA)

func erfolgreichEinScreenshotErstellt() -> Bool{
    let task = Process()
    task.launchPath = "/usr/sbin/screencapture"
    task.arguments = ["-c"]
    task.launch()
    task.waitUntilExit()
    let status = task.terminationStatus
    return status == 0
}

func dasBildAbholenUndZeigen() -> NSImage {
    let pasteboard = NSPasteboard.general
    guard pasteboard.canReadItem(withDataConformingToTypes:
        NSImage.imageTypes) else{
        return NSImage()
    }
    guard let image = NSImage(pasteboard: pasteboard) else {
        return NSImage()
    }
    let tiffData = image.tiffRepresentation!
    let pngData = NSBitmapImageRep(data: tiffData)?.representation(using: .png, properties: [:])
    return image
}

Everything works fine till here!

The last step I like to do, I need a little help for: how can I save the "image" as a .png-file with a given name to my desktop for further use, i.e. generating a pdf file or so from the png file.

As you can see, I've tried the following code but than I've got stuck:

    .........
    let tiffData = image.tiffRepresentation!
    let pngData = NSBitmapImageRep(data: tiffData)?.representation(using: .png, properties: [:])

Thanks in advance, if someone likes to help me with some code or a hint to a solution idea.

Best

Thomas

Why not save png file directly ? If it is in the pasteBoard, you can also save manually by pasting in Preview.

Hi Claude31,

tanks for your reply.

Manually I just tried and it doesn't work. I'm not getting a past function by doing a right hand side click or a png file by using the shortcut "command v".

The point is: I like to make automatically a collection of screenshots from the moment on, when the connection to my cloud isn't available until the connection is back again, controlled by a timer with let's say 5-10 Minutes. The collection then will be converted to one! pdf file manually via Adobe Acrobat DC (which is very easy) as a proof for the connection quality. The screenshots capture the time, date and the status "offline" or "online". The information based on the fact that the connection to the cloud was lost, I'm getting through the E-Mail my app is generating on the two moments "offline" and "online".

Therefore I need all the png's.

Best

Thomas

SwiftUI on macOS, app generating a png file on the desktop from a screenshot made to the pasteboard
 
 
Q