Nishad Arora Nishad Arora - 1 year ago 91
Swift Question

how to use writeToFile to save image in document directory?

// directoryPath is a URL from another VC
@IBAction func saveButtonTapped(sender: AnyObject) {
let directoryPath = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let urlString : NSURL = directoryPath.URLByAppendingPathComponent("Image1.png")
print("Image path : \(urlString)")
if !NSFileManager.defaultManager().fileExistsAtPath(directoryPath.absoluteString) {
UIImageJPEGRepresentation(self.image, 1.0)!.writeToFile(urlString.absoluteString, atomically: true)
displayImageAdded.text = "Image Added Successfully"
} else {
displayImageAdded.text = "Image Not Added"
print("image \(image))")
}
}


I am not getting any error but the Image is not getting saved in the document.

Answer Source

The problem there is that you are checking if the folder not exists you should check the file exists. Also you should use url.path! instead of url.absoluteString. You are also saving your a jpeg image using a png file extension. You should use .jpg.

let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
// create a name for your image
let fileURL = documentsDirectoryURL.URLByAppendingPathComponent("Image1.jpg")

if !NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) {
    if UIImageJPEGRepresentation(image, 1.0)!.writeToFile(fileURL.path!, atomically: true) {
        print("file saved")
    } else {
        print("error saving file")
    }
} else {
    print("file already exists")
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download