将图像文件保存到临时目录
我有一个名为“Image.png”的图像文件,并将其保存在我的主包(Project Navigator层次结构中的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 }
虽然我不确定你为什么要这样做,而不是直接访问bundle资源。
Swift 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 }