「Image.png」という名前の画像ファイルがあり、メイン バンドル (Project Navigator 階層の ViewController.swift ファイルのすぐ横) に保存されます。このイメージのコピーを一時ディレクトリに保存したいと考えています。今までやったことがないのですが、どのコードを使用できますか?
15524 次
3 に答える
21
このようなものがうまくいくはずです。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
}
ただし、バンドル リソースに直接アクセスするのではなく、なぜこれを行う必要があるのか 、よくわかりません。
于 2016-03-03T01:27:49.290 に答える
4
これがSwift 5の答えです
/**
* Copy a resource from the bundle to the temp directory.
* Returns either URL of location in temp directory, or nil upon failure.
*
* Example: copyBundleResourceToTemporaryDirectory("kittens", "jpg")
*/
public func copyBundleResourceToTemporaryDirectory(resourceName: String, fileExtension: String) -> URL?
{
// Get the file path in the bundle
if let bundleURL = Bundle.main.url(forResource: resourceName, withExtension: fileExtension) {
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
// Create a destination URL.
let targetURL = tempDirectoryURL.appendingPathComponent(resourceName).appendingPathExtension(fileExtension)
// Copy the file.
do {
try FileManager.default.copyItem(at: bundleURL, to: targetURL)
return targetURL
} catch let error {
print("Unable to copy file: \(error)")
}
}
return nil
}
一時ファイルの詳細については、この記事を読むことをお勧めします
于 2020-10-15T12:27:56.837 に答える