ios 使用Swift删除iOS目录中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34369616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete files in iOS directory using Swift
提问by Fabian Boulegue
I downloaded some PDF files in my app and want to delete these on closing the application.
我在我的应用程序中下载了一些 PDF 文件,并希望在关闭应用程序时删除这些文件。
For some reason it does not work:
由于某种原因,它不起作用:
Creating the file:
创建文件:
let reference = "test.pdf"
let RequestURL = "http://xx/_PROJEKTE/xx\(self.reference)"
let ChartURL = NSURL(string: RequestURL)
//download file
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
let destinationUrl = documentsUrl.URLByAppendingPathComponent(ChartURL!.lastPathComponent!)
if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
print("The file already exists at path")
} else {
// if the file doesn't exist
// just download the data from your url
if let ChartDataFromUrl = NSData(contentsOfURL: ChartURL!){
// after downloading your data you need to save it to your destination url
if ChartDataFromUrl.writeToURL(destinationUrl, atomically: true) {
print("file saved")
print(destinationUrl)
} else {
print("error saving file")
}
}
}
Then I want to call the test()
function to remove the items, like this:
然后我想调用该test()
函数来删除项目,如下所示:
func test(){
let fileManager = NSFileManager.defaultManager()
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
do {
let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")
for filePath in filePaths {
try fileManager.removeItemAtPath(NSTemporaryDirectory() + filePath)
}
} catch {
print("Could not clear temp folder: \(error)")
}
}
采纳答案by TwoStraws
I believe your problem is on this line:
我相信你的问题是在这条线上:
let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")
You're using contentsOfDirectoryAtPath()
with something that is an NSURL
. You choose either path strings or URLs, not try to mix them both. To pre-empty your possible next question, URLs are preferred. Try using contentsOfDirectoryAtURL()
and removeItemAtURL()
.
您正在使用contentsOfDirectoryAtPath()
的东西,是一个NSURL
。您可以选择路径字符串或 URL,而不是尝试将两者混合使用。为了预先清空您可能的下一个问题,首选 URL。尝试使用contentsOfDirectoryAtURL()
和removeItemAtURL()
。
Another curious thing you should look at once you resolve the above: why are you using NSTemporaryDirectory()
for the file path when you try to delete? You're reading the document directory and should use that.
解决上述问题后,您应该看看另一件奇怪的事情:为什么NSTemporaryDirectory()
在尝试删除时使用文件路径?您正在阅读文档目录,应该使用它。
回答by Saleh Masum
This code works for me. I removed all the images that were cached.
这段代码对我有用。我删除了所有缓存的图像。
private func test(){
let fileManager = NSFileManager.defaultManager()
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL
let documentsPath = documentsUrl.path
do {
if let documentPath = documentsPath
{
let fileNames = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
print("all files in cache: \(fileNames)")
for fileName in fileNames {
if (fileName.hasSuffix(".png"))
{
let filePathName = "\(documentPath)/\(fileName)"
try fileManager.removeItemAtPath(filePathName)
}
}
let files = try fileManager.contentsOfDirectoryAtPath("\(documentPath)")
print("all files in cache after deleting images: \(files)")
}
} catch {
print("Could not clear temp folder: \(error)")
}
}
**** Update swift 3 ****
**** 更新 swift 3 ****
let fileManager = FileManager.default
let documentsUrl = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL
let documentsPath = documentsUrl.path
do {
if let documentPath = documentsPath
{
let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
print("all files in cache: \(fileNames)")
for fileName in fileNames {
if (fileName.hasSuffix(".png"))
{
let filePathName = "\(documentPath)/\(fileName)"
try fileManager.removeItem(atPath: filePathName)
}
}
let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
print("all files in cache after deleting images: \(files)")
}
} catch {
print("Could not clear temp folder: \(error)")
}