我在我的应用程序中下载了一些PDF文件,并希望在关闭应用程序时删除这些文件.
由于某种原因,它不起作用:
创建文件:
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") } } }
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)") } }
我相信你的问题就在这条线上:
let filePaths = try fileManager.contentsOfDirectoryAtPath("\(documentsUrl)")
您正在使用contentsOfDirectoryAtPath()和NSURL.您可以选择路径字符串或URL,而不是尝试将它们混合使用.要预先清空您可能的下一个问题,首选网址.尝试使用contentsOfDirectoryAtURL()和removeItemAtURL().
解决上述问题后,您应该注意另一个奇怪的事情:为什么在尝试删除时使用NSTemporaryDirectory()作为文件路径?您正在阅读文档目录并应该使用它.