给定一个路径[[self documentsDirectory] stringByAppendingPathComponent:@"myFiles/aFile.txt"]
的文件,如何删除我的应用文档目录中的文件?
答案 0 :(得分:96)
NSFileManager是一个非常方便的工具:
[[NSFileManager defaultManager] removeItemAtPath: pathToFile error: &error];
答案 1 :(得分:5)
使用Swift 3,FileManager
有一个名为removeItem(at:)
的方法。 removeItem(at:)
有以下声明:
func removeItem(at URL: URL) throws
删除指定网址的文件或目录。
下面的代码片段显示了如何使用removeItem(at:)
删除文件:
do {
try FileManager.default.removeItem(at: fileUrl)
} catch {
print("Could not delete file: \(error)")
}
作为一个完整的示例,以下UIViewController
子类实现显示了如何将文件从应用程序包复制到文档目录中的特定URL,删除文档目录中特定URL的文件并检查是否存在文件存在于文档目录中的特定URL:
import UIKit
class ViewController: UIViewController {
@IBAction func copyFile(_ sender: UIButton) {
// Get app bundle file url
guard let bundleFileUrl = Bundle.main.url(forResource: "Movie", withExtension: "mov") else { return }
// Create a destination url in document directory for file
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")
// Copy bundle file to document directory
if !FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
do {
try FileManager.default.copyItem(at: bundleFileUrl, to: documentDirectoryFileUrl)
} catch {
print("Could not copy file: \(error)")
}
}
}
@IBAction func deleteFile(_ sender: UIButton) {
// Get destination url in document directory for file
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let documentDirectoryFileUrl = documentsDirectory.appendingPathComponent("Movie.mov")
// Delete file in document directory
if FileManager.default.fileExists(atPath: documentDirectoryFileUrl.path) {
do {
try FileManager.default.removeItem(at: documentDirectoryFileUrl)
} catch {
print("Could not delete file: \(error)")
}
}
}
@IBAction func checkIfFileExist(_ sender: UIButton) {
// Get destination url in document directory for file
guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let outputUrl = documentsDirectory.appendingPathComponent("Movie.mov")
// Print if file exists in document directory or not
FileManager.default.fileExists(atPath: outputUrl.path) ? print("File exists") : print("File does not exist")
}
}
答案 2 :(得分:0)
对于Swift 3.x和Xcode 8.x
var featureLayer = new FeatureLayer({
url: "https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Census_Tract_Areas_analysis_trim/FeatureServer/0",
outFields: ["*"],
renderer: renderer,
definitionExpression: "FIPS IN (" + fips + ")"
});