Ho scaricato alcuni file PDF nella mia app e desidero eliminarli alla chiusura dell'applicazione.Elimina i file nella directory iOS utilizzando Swift
Per qualche ragione non funziona:
Creazione del 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")
}
}
}
Poi voglio chiamare la funzione test()
per rimuovere gli elementi, in questo modo:
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)")
}
}
Ho il sospetto che si vuole considerare l'utilizzo di '.CachesDirectory' piuttosto che' .DocumentDirectory' per il salvataggio e l'eliminazione di questi file. – TwoStraws
ho provato a salvare il mio file ma non ha funzionato –
Dovresti assolutamente leggere [best practice di backup app] (https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/PerformanceTips /PerformanceTips.html#//apple_ref/doc/uid/TP40007072-CH7-SW17) e [QA1719] (https://developer.apple.com/library/ios/qa/qa1719/_index.html) quindi. – TwoStraws