ios - 无法将文件保存在 tmp 目录中
<p><p>我有这个功能可以将图像保存在 tmp 文件夹中</p>
<pre><code>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)
}
}
</code></pre>
<p>但是当我打开我的应用程序的临时文件夹时,它是空的。将图像保存在临时文件夹中我做错了什么?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p><code>absoluteString</code> 不是获取文件路径的正确方法
<code>NSURL</code>,使用 <code>path</code> 代替:</p>
<pre><code>let targetPath = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg").path!
data.writeToFile(targetPath, atomically: true)
</code></pre>
<p>或者<em>更好,</em>只使用 URL:</p>
<pre><code>let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(name).jpg")
data.writeToURL(targetURL, atomically: true)
</code></pre>
<p>更好的是,使用 <code>writeToURL(url: options) throws</code>
并检查成功或失败:</p>
<pre><code>do {
try data.writeToURL(targetURL, options: [])
} catch let error as NSError {
print("Could not write file", error.localizedDescription)
}
</code></pre>
<p><strong>Swift 3/4 更新:</strong></p>
<pre><code>let targetURL = tempDirectoryURL.appendingPathComponent("\(name).jpg")
do {
try data.write(to: targetURL)
} catch {
print("Could not write file", error.localizedDescription)
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 无法将文件保存在 tmp 目录中,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/39336698/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/39336698/
</a>
</p>
页:
[1]