无法在tmp目录中保存文件 [英] Can not save file inside tmp directory

查看:443
本文介绍了无法在tmp目录中保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能将图像保存在tmp文件夹中

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?

推荐答案

absoluteString 不是正确的方法来获取
的文件路径 NSURL ,而是使用路径

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)

更好,仅使用URL:

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

更好的是,使用 writeToURL(url:options)抛出
并检查成功或失败:

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更新:

let targetURL = tempDirectoryURL.appendingPathComponent("\(name).jpg")
do {
    try data.write(to: targetURL)
} catch {
    print("Could not write file", error.localizedDescription)
}

这篇关于无法在tmp目录中保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆