Ich habe einige PDF-Dateien in meine App heruntergeladen und möchte diese beim Schließen der Anwendung löschen.Löschen von Dateien im iOS-Verzeichnis mithilfe von Swift
Aus irgendeinem Grund funktioniert es nicht:
Erstellen der Datei:
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")
}
}
}
Dann möchte ich die test()
Funktion aufrufen, um die Elemente zu entfernen, wie folgt aus:
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)")
}
}
Ich vermute, Sie wollen '.CachesDirectory' zu prüfen, mit anstatt' .DocumentDirectory' zum Speichern und Löschen dieser Dateien. – TwoStraws
Ich habe versucht, meine Datei dort zu speichern, aber es hat nicht funktioniert –
Sie sollten auf jeden Fall [App Backup Best Practices] lesen (https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/PerformanceTips /PerformanceTips.html#//apple_ref/doc/uid/TP40007072-CH7-SW17) und [QA1719] (https://developer.apple.com/library/ios/qa/qa1719/_index.html) dann. – TwoStraws