将图像文件保存到临时目录 [英] Save image file to temp directory
本文介绍了将图像文件保存到临时目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为Image.png的图像文件,它保存在我的主包中(位于Project Navigator层次结构中的ViewController.swift文件旁边)。我想将此映像的副本保存到临时目录。我以前从来没有这样做过,我可以使用哪些代码?
I have an image file named "Image.png", and it is saved in my main bundle (right beside the ViewController.swift file in the Project Navigator hierarchy). I want to save a copy of this image to the temporary directory. I've never done it before, what code could I use please?
推荐答案
这样的事情可以解决问题。我假设你想要在Swift中得到答案。
Something like this should do the trick. I'm assuming you wanted the answer in 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
}
虽然,我不确定你为什么要这样做而不是直接访问捆绑资源。
Although, I'm not really sure why you would want to do this rather than directly accessing the bundle resource.
这篇关于将图像文件保存到临时目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文