Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/108.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 无法将文件保存在tmp目录中_Ios_Swift - Fatal编程技术网

Ios 无法将文件保存在tmp目录中

Ios 无法将文件保存在tmp目录中,ios,swift,Ios,Swift,我有这个功能来保存tmp文件夹内的图像 private func saveImageToTempFolder(image: UIImage, withName name: String) { if let data = UIImageJPEGRepresentation(image, 1) { let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)

我有这个功能来保存tmp文件夹内的图像

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

但当我打开应用程序的临时文件夹时,它是空的。将图像保存在临时文件夹中有什么不对吗?

absoluteString
不是获取文件路径的正确方法 对于
NSURL
,请改用
path

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)抛出
并检查成功或失败:

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

谢谢你,我正在使用的网址只选择节省了我的很多时间。我第一次使用绝对字符串,但没有得到任何工作。密钥为路径。非常感谢!尝试将此代码应用于缓存目录时出现此错误。无法写入文件。文件“jd64q7sc5n.png”不存在