objective-cmacosswiftxcode6

NSPNGFileType - not found in Swift?


Today, I found something strange :

I wanted to write this code in swift :

    NSData *data = [myImage representationUsingType: NSPNGFileType properties: nil];

In swift it's look like this:

var data: NSData = imageToSave?.representationUsingType( NSPNGFileType ,
            properties: nil)

The problem is that the compiler say : " Use of unresolved identifier 'NSPNGFileType'". Does anyone have any idea why ?

Thanks, and sorry for my english !


Solution

  • Convert the NSImage to tiff and then get the data using .png in Swift 5+.

    To get the image data:

    if let tiffRepresentation = icon.tiffRepresentation,
       let imageRep = NSBitmapImageRep(data: tiffRepresentation) {
        let data = imageRep.representation(using: .png, properties: [:])
        
       // Use the data
    } 
    

    If you want to save the image, you can write something like this:

    For Mac apps, you may need to add "Capabilities" to save the file. Enable Read/Write for "Downloads Folder" in the App Sandbox.

    let downloads = FileManager.default.homeDirectoryForCurrentUser.appending(component: "Downloads")
    let path = downloads.appending(components: "image.png")
    if let tiffRepresentation = icon.tiffRepresentation,
       let imageRep = NSBitmapImageRep(data: tiffRepresentation) {
        let data = imageRep.representation(using: .png, properties: [:])
        do {
            try data?.write(to: path, options: .atomic)
        } catch {
            print("Error saving: path\(path) error: \(error)")
        }
    } else {
        print("Invalid image")
    }