Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not save file inside tmp directory

Tags:

ios

swift

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?

like image 637
pableiros Avatar asked Mar 23 '26 05:03

pableiros


1 Answers

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)
}

Swift 3/4 update:

let targetURL = tempDirectoryURL.appendingPathComponent("\(name).jpg")
do {
    try data.write(to: targetURL)
} catch {
    print("Could not write file", error.localizedDescription)
}
like image 83
Martin R Avatar answered Mar 25 '26 19:03

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!