2016-03-03 62 views
1

我有一個名爲「Image.png」的圖像文件,並將其保存在我的主包(Project Navigator層次結構中的ViewController.swift文件右側)中。我想將此圖像的副本保存到臨時目錄。我從來沒有做過,我可以使用哪些代碼?將圖像文件保存到臨時目錄

回答

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

多謝,馬特! – dimery2006

+0

沒有問題@ dimery2006,如果它幫助請考慮接受答案:) – mszaro

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