![](/img/trans.png)
[英]UITableView is not reloading after I delete all files from Document Directory
[英]Swift delete all files from particular Document Directory Location
我的場景,我正在嘗試使用文檔文件夾路徑從特定文檔目錄中刪除所有文件。 在這里,每次我在我的應用程序文檔目錄文件夾中保存文件時,通過使用下面的代碼,我無法刪除文件
let urlString: String = myurl.absoluteString
print("FILEURL:\(urlString)")
do {
try fm.removeItem(atPath: "\(myurl)")
} catch let error as NSError {
print(error.debugDescription)
}
您正在混淆 URL 和字符串路徑
要么使用String
相關的 API
try fm.removeItem(atPath: myurl.path) // NEVER use .absoluteString for a file system path
或者使用URL
相關的 API(推薦)
try fm.removeItem(at: myurl)
要刪除所有文件,請使用contentsOfDirectory(at:includingPropertiesForKeys:options:)
獲取封閉目錄中的文件 URL 並一一刪除
let fileManager = FileManager.default
do {
let documentDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURLs = try fileManager.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for url in fileURLs {
try fileManager.removeItem(at: url)
}
} catch {
print(error)
}
使用 Url 刪除特定文件或文件夾
let filePathString = "file:///Users/mac-01/Library/Developer/CoreSimulator/Devices/092D2386-5B43-4D98-8DCF-F21E08CCD400/data/Containers/Data/Application/C6D910A2-67D9-48A4-8221-5C81C722D508/Documents/Products"
guard let fileUrl = URL(string: "\(filePathString)") else { return }
do {
try FileManager.default.removeItem(at: fileUrl)
print("Remove successfully")
}
catch let error as NSError {
print("An error took place: \(error)")
}
removeItem 方法是接受文檔目錄文件或文件夾的 url。請嘗試使用它。
對於刪除文檔目錄文件夾使用
let fileManager = FileManager.default
let myDocuments = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
try fileManager.removeItem(at: myDocuments)
} catch {
return
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.