我有一个名为“Image.png”的图像文件,它保存在我的主包中(位于项目导航器层次结构中的 ViewController.swift 文件旁边)。我想将此图像的副本保存到临时目录。我以前没有做过,请问我可以使用什么代码?
像这样的事情应该可以解决问题。我假设您想在 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
}
虽然,我不太确定为什么您想要这样做而不是直接访问捆绑资源。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)