我有一個名爲「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