2015-12-02 30 views
3

我有一個項目正在將數據保存到PDF中。這個代碼是:iOS:使用Swift2刪除.DocumentDirectory中的文件

// 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 

    } 

} 

我試着在網上找到了答案,但無法找到斯威夫特2.任何人可以幫?

我試過這個,但沒有運氣的工作:

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

我只是想刪除特定項目刷卡,並在DocumentDirectory並不是所有的數據。

回答

7

removeItemAtPath:error:是Objective-C的版本。對於SWIFT,你要removeItemAtPath,像這樣:

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

在迅速,與將throw方法時,這是一個相當常見的模式 - 與try前綴的呼叫,並在do-catch包圍。你會用錯誤指針來做更少的事情,然後你會在objective-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 
}