Randy Randy - 2 months ago 13
Swift Question

NSData writeToFile method returns true but file is not written to the disk

I have developed an OS X app and I sometimes need to save some pictures on the disk. I have a method to do that :

func saveImageAtPath(image: NSImage, path: String)
{
if let data = image.TIFFRepresentation
{
let bitmap = NSBitmapImageRep(data: data)
let pngImage = bitmap?.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:])

NSLog("Path : %@", path)

if let _ = pngImage?.writeToFile(path, atomically: false)
{
NSLog("Everything should work...")
}
}
}


When I try to save an image, everything seems to work, the following text is displayed in the console :


Path :
/Users/myusername/Documents/Pictures/Apps/testPictures/mypicture.png

Everything should work...


Everything was working perfectly a month ago.
Here is my conf :

OS X Yosemite 10.10.5
Xcode 7.2

If anyone has an idea... That'd be great !

Thanks in advance.

Answer

I spent all day trying to figure out how to code up the suggested fix in swift 2.0 , so I wanted to share now that I have it working

do{
    let result = try Bool(pngImage!.writeToFile(filePath, options: NSDataWritingOptions.DataWritingAtomic))
}
catch let error as NSError {
    print(error.localizedDescription)
}

I hope that saves someone some time.