2015-12-02 1 views
3

У меня есть проект, над которым я работаю, что сохраняет данные в PDF. Код для этого:iOS: удалить файл в .DocumentDirectory с помощью Swift2

// Save PDF Data 

let recipeItemName = nameTextField.text 

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 

pdfData.writeToFile("\(documentsPath)/\(recipeFileName).pdf", atomically: true) 

Я могу просматривать файлы в отдельном UITableView у меня в другом ViewController. Когда пользователь перебирает UITableViewCell, я хочу, чтобы он также удалял элемент из .DocumentDirectory. Мой код UITableView удаляемых:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 

    if editingStyle == .Delete { 

     // Delete the row from the data source 

     savedPDFFiles.removeAtIndex(indexPath.row) 

     // Delete actual row 

     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 


     // Deletion code for deleting from .DocumentDirectory here??? 


    } else if editingStyle == .Insert { 

     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 

    } 

} 

Я пытался найти ответ в Интернете, но не могу найти что-нибудь для Swift 2. Может кто-то пожалуйста, помогите?

Я пытался работать с этим, но не повезло:

var fileManager:NSFileManager = NSFileManager.defaultManager() 
var error:NSErrorPointer = NSErrorPointer() 
fileManager.removeItemAtPath(filePath, error: error) 

Я просто хочу, чтобы удалить конкретный элемент прокатывается и не все данные в DocumentDirectory.

ответ

7

removeItemAtPath:error: является версия Objective-C. Для стрижа, вы хотите removeItemAtPath, как это:

do { 
     try NSFileManager.defaultManager().removeItemAtPath(path) 
    } catch {} 

В быстры, это довольно распространенной схеме при работе с методами, которые будут throw - префикс вызова с try и заключающими в do-catch. Вы будете делать меньше с указателями ошибок, чем в объективе-c. Вместо этого ошибки должны быть пойманы или, как и в вышеприведенном фрагменте, игнорируются. Чтобы поймать и обработать ошибку, вы можете сделать свое удаление следующим образом:

do { 
     let fileManager = NSFileManager.defaultManager() 
     let documentDirectoryURLs = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) 

     if let filePath = documentDirectoryURLs.first?.URLByAppendingPathComponent("myFile.pdf").path { 
      try fileManager.removeItemAtPath(filePath) 
     } 

    } catch let error as NSError { 
     print("ERROR: \(error)") 
    } 
+1

Спасибо. Я ценю это. Я немного поправился, чтобы работать с моим проектом. – ChallengerGuy

1

Что вы хотите сделать, это получить recipeFileName из отредактированной ячейки, чтобы восстановить путь к файлу.

Непонятно, как вы заполняете свои данные UITableViewCell, поэтому я расскажу о наиболее распространенном сценарии.

Предположим, у вас есть массив файлов, которые вы используете для заполнения dataSource.

let recipeFiles = [RecipeFile]() 

с RecipeFile структуры

struct RecipeFile { 
    var name: String 
} 

В tableView(_:cellForRowAtIndexPath:), вы, вероятно, установить recipeFile так:

cell.recipeFile = recipeFiles[indexPath.row] 

так в tableView(_:commitEditingStyle:forRowAtIndexPath:), вы можете получить имя файла, как это:

let recipeFile = recipeFiles[indexPath.row] 

и удалить файл

var fileManager:NSFileManager = NSFileManager.defaultManager() 
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 
let filePath = "\(documentsPath)/\(recipeFile.name).pdf" 
do { 
    fileManager.removeItemAtPath(filePath, error: error) 
} catch _ { 
    //catch any errors 
} 
Смежные вопросы