2017-02-04 21 views
1
func getDocumentsDirectory() -> URL { 
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 
    let documentsDirectory = paths[0] 
    return documentsDirectory 
} 

所以只需使用快捷文件,我得到使用function.And它正確返回,現在我的名,我怎麼能刪除使用雨燕3這個文件? 和我怎樣才能讀取像UIImageJPEGRepresentation刪除IOS

let image_data = UIImageJPEGRepresentation(self.commons.correctlyOrientedImage(image: self.imageSelected.image!),0.5) 

我沒有跟蹤和它不工作

let filename = getDocumentsDirectory().appendingPathComponent("l.png") let 

文件管理器= FileManager.default VAR文件路徑=文件名 //檢查文件是否存在

   if fileManager.fileExists(atPath: filePath.absoluteString) { 
        // Delete file 
        try fileManager.removeItem(atPath: filePath.absoluteString) 
       } else { 
        print("File does not exist") 
       } 

我像這樣保存文件

let filename = getDocumentsDirectory().appendingPathComponent("COPY111.PNG") 
     try? image_data?.write(to: filename) 

但我不能從下面

回答

2

提供的答案刪除有刪除文件的行:

do { 
    try FileManager.default.removeItem(at: fileName) 
} catch let error as NSError { 
    print("Error: \(error.domain)") 
} 

而這裏的代碼,將其設置爲ImageView的:

if let image = UIImage(contentsOfFile: fileName) { 
    imageView.image = image 
} 
1

試試這個。希望這將work.To 刪除文件

let fileNameToDelete = "myFileName.txt" 
    var filePath = "" 

    // Fine documents directory on device 
    let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) 

    if dirs.count > 0 { 
     let dir = dirs[0] //documents directory 
     filePath = dir.appendingFormat("/" + fileNameToDelete) 
     print("Local path = \(filePath)") 

    } else { 
     print("Could not find local directory to store file") 
     return 
    } 


    do { 
     let fileManager = FileManager.default 

     // Check if file exists 
     if fileManager.fileExists(atPath: filePath) { 
      // Delete file 
      try fileManager.removeItem(atPath: filePath) 
     } else { 
      print("File does not exist") 
     } 

    } 
    catch let error as NSError { 
     print("An error took place: \(error)") 
    } 

來源:http://swiftdeveloperblog.com/code-examples/delete-file-example-in-swift/

對於圖像加載

let imageData = UIImageJPEGRepresentation(image)! 
let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) 
let imageURL = docDir.appendingPathComponent("tmp.jpeg") 
try! imageData.write(to: imageURL) 

let newImage = UIImage(contentsOfFile: imageURL.path)! 
+0

我編輯我的第一篇文章,我做了UR解決方案,但我得到文件沒有存在 –

+0

我得到文件路徑,但刪除它說文件不存在filePath /var/mobile/Containers/Data/Application/D5FA0123-65A2-470 A-A817-8871F984CE90/Documents/profile-FFCEBEA9-2F8D-49E2-9A09-2BF87BD0B542 - A9636AF4-350D-4D72-A4BD-E4F2B183F4BB.png filePath 文件不存在 –