我有一个名为“Image.png”的图像文件,并将其保存在我的主包(Project Navigator层次结构中的ViewController.swift文件右侧)中。我想将此图像的副本保存到临时目录。我从来没有做过,我可以使用哪些代码?将图像文件保存到临时目录
1
A
回答
9
像这样的东西应该做的伎俩。我假设你想在Swift中得到答案。
/**
* Copy a resource from the bundle to the temp directory.
* Returns either NSURL of location in temp directory, or nil upon failure.
*
* Example: copyBundleResourceToTemporaryDirectory("kittens", "jpg")
*/
public func copyBundleResourceToTemporaryDirectory(resourceName: String, fileExtension: String) -> NSURL?
{
// Get the file path in the bundle
if let bundleURL = NSBundle.mainBundle().URLForResource(resourceName, withExtension: fileExtension) {
let tempDirectoryURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
// Create a destination URL.
let targetURL = tempDirectoryURL.URLByAppendingPathComponent("\(resourceName).\(fileExtension)")
// Copy the file.
do {
try NSFileManager.defaultManager().copyItemAtURL(bundleURL, toURL: targetURL)
return targetURL
} catch let error {
NSLog("Unable to copy file: \(error)")
}
}
return nil
}
虽然我不确定为什么要这样做,而不是直接访问bundle资源。
0
斯威夫特4.x的版本mszaro的回答
/**
* Copy a resource from the bundle to the temp directory.
* Returns either NSURL of location in temp directory, or nil upon failure.
*
* Example: copyBundleResourceToTemporaryDirectory("kittens", "jpg")
*/
public func copyBundleResourceToTemporaryDirectory(resourceName: String, fileExtension: String) -> NSURL?
{
// Get the file path in the bundle
if let bundleURL = Bundle.main.url(forResource: resourceName, withExtension: fileExtension) {
let tempDirectoryURL = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)
// Create a destination URL.
let targetURL = tempDirectoryURL.appendingPathComponent("\(resourceName).\(fileExtension)")
// Copy the file.
do {
try FileManager.default.copyItem(at: bundleURL, to: targetURL)
return targetURL as NSURL
} catch let error {
NSLog("Unable to copy file: \(error)")
}
}
return nil
}
+1
'NSURL'不适用于Swift 4.不要使用它。附加文件名和扩展名的正确语法是'let targetURL = tempDirectoryURL.appendingPathComponent(resourceName).appendingPathExtension(fileExtension))' – vadian
相关问题
- 1. 如何将图像和录制文件保存在临时目录中?
- 2. 如何从文件浏览器将文件保存到临时目录
- 3. Android:将图像保存到目录
- 4. 将图像保存到目录c#
- 5. 将临时图像文件保存在会话中
- 6. 将图像保存到文件目录中vs将图像保存到数据库中
- 7. Powershell:将文件保存到根目录
- 8. 将matplotlib文件保存到目录
- 9. 将文件保存到当前目录
- 10. 将文件保存到目录中
- 11. 我尝试每隔30秒将临时目录保存为临时目录,但每次只能保存一次
- 12. 调整图像大小并将图像保存到新目录
- 13. Android临时保存位图图像
- 14. 保存临时文件
- 15. 将图像保存到文档目录中
- 16. 保存到临时csv文件
- 17. 将文件保存到临时文件夹
- 18. 将文件从临时目录复制到资源文件夹
- 19. 将解码的临时图像保存到Django Imagefield
- 20. Android:将图像存储到项目目录(文件)?
- 21. 将gradle临时缓存目录移动到其他目录
- 22. Android:将图像保存到文件夹
- 23. C#:将图像保存到文件夹
- 24. MediaElement将图像(帧)保存到文件
- 25. 将图像保存到文件
- 26. Codeigniter |将Base64图像保存到文件
- 27. Java将CMYK图像保存到文件
- 28. 保存图像到一个目录
- 29. 负荷文档目录保存图像
- 30. 文档目录保存图像
多谢,马特! – dimery2006
没有问题@ dimery2006,如果它帮助请考虑接受答案:) – mszaro