pableiros pableiros - 3 months ago 16
iOS Question

Can not save file inside tmp directory

I have this function to save an image inside the tmp folder

private func saveImageToTempFolder(image: UIImage, withName name: String) {

if let data = UIImageJPEGRepresentation(image, 1) {
let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg").absoluteString
print("target: \(targetURL)")
data.writeToFile(targetURL, atomically: true)
}
}


But when I open the temp folder of my app, it is empty. What am I doing wrong to save the image inside the temp folder?

Answer

absoluteString is not the correct method to get a file path of an NSURL, use path instead:

let targetPath = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg").path!
data.writeToFile(targetPath, atomically: true)

Or better, work with URLs only:

let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg")
data.writeToURL(targetURL, atomically: true)

Even better, use writeToURL(url: options) throws and check for success or failure:

do {
    try data.writeToURL(targetURL, options: [])
} catch let error as NSError {
    print("Could not write file", error.localizedDescription)
}
Comments