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

Так просто, я получаю свое имя файла, используя эту функцию. И теперь он корректно возвращается, как я могу удалить этот файл с помощью Swift 3? И как я могу прочитать изображение назад, как UIImageJPEGRepresentation?удалить файл с помощью swift in ios

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

я следующий, и его не работает

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

FileManager = FileManager.default вар Filepath = имя_файла // Проверяем, если файл существует

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

I сохранить файл, подобный этому

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

Я отредактировал мой первый пост, я сделал ур решение, но я получаю file does nto существует –

+0

Я получаю путь к файлу, но при удалении он говорит, что файл не существует filePath /var/mobile/Контейнеры/Данные/Приложение/D5FA0123-65A2-470 A-A817-8871F984CE90/Документы/профиль-FFCEBEA9-2F8D-49E2-9A09-2BF87BD0B542 - A9636AF4-350D-4D72-A4BD-E4F2B183F4BB.png filePath Файл не существует –