2

I am getting an error when writing an image file to a directory in Xcode. The function data.writeToFile is returning an error. Here is what I am trying to do:

Get The File Path:

func getPath(fileName: String) -> String {
        let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        let folder = "sampleDirectory"
        return documentURL.URLByAppendingPathComponent(folder).URLByAppendingPathComponent(fileName).path!
    }

Save the Image

func saveImage(image: UIImage, path: String) -> Bool {
        let pngImageData = UIImagePNGRepresentation(image)
        do {
            let success = try pngImageData?.writeToFile(path, options: NSDataWritingOptions.init(rawValue: 0))
        } catch {
            print(error)
        }
        return false
    }

However, there is an error saying:

NSPOSIXErrorDomain - code : 2

Does anyone know what the problem could be?

EDIT Where I call the code:

let fileName = "first_image"
let imagePath = self.getPath(fileName)
let result = self.saveImage(processedImage, path: imagePath)

processedImage is of type UIImage!

hockeybro
  • 985
  • 1
  • 9
  • 33

1 Answers1

1

Try creating the directory "sampleDirectory" if it does not exists or don't use a subdirectory. You can check if the directory exists with:

if !NSFileManager.defaultManager().fileExistsAtPath(path) { // create missing directories try! NSFileManager.defaultManager().createDirectoryAtPath(foo, withIntermediateDirectories: true, attributes: nil) }

You also might want to use the option NSDataWritingOptions.DataWritingAtomic which first write to an auxiliary file first and then exchange the files if there were no errors

n6xej
  • 351
  • 4
  • 12