Question

I have a newsstand app which has magazines and uses the newsstand framework. I realized there was something wrong when deleting the magazines and/or when downloading them because when I accessed settings/usage my app keeps growing in memory usage when downloading and deleting the same magazine. Found the issue... when downloading the issue in the delegate method:

-(void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL

I just needed to add something like this at the end:

NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:[destinationURL path] error:&error];
if (error){
    NSLog(@"ERROR:%@", error);
}

Even the directory is called "caches" you need to manually delete. Ok problem solved but what about the customers who already download my app and have tons of MBs dead in the cache directory.

I wanted to know how to get this directory and delete everything on it at launch and only once... I can do it only once using a NSUserdefault but how do I get this directory and delete any zip files in it... an example of this directory and a file within is:

/private/var/mobile/Applications/1291CC20-C55F-48F6-86B6-B0909F887C58/Library/Caches/bgdl-280-6e4e063c922d1f58.zip

but this path varies with the device. I want to do this at launch so I'm sure there are no downloads in progress but any other solutions are welcome, thanks in advance.

Was it helpful?

Solution

Everything that you need is enumerate all files from Caches directory and remove ones that have zip extension:

- (void)removeZipFilesFromCachesDirectory {
    static NSString *const kZIPExtension = @"zip";

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *cachesDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSError *error = nil;
    NSArray *fileNames = [fileManager contentsOfDirectoryAtPath:cachesDirectoryPath error:&error];
    if (error == nil) {
        for (NSString *fileName in fileNames) {
            NSString *filePath = [cachesDirectoryPath stringByAppendingPathComponent:fileName];
            if ([filePath.pathExtension.lowercaseString isEqualToString:kZIPExtension]) {
                NSError *anError = nil;
                [fileManager removeItemAtPath:filePath error:&anError];
                if (anError != nil) {
                    NSLog(@"%@", anError);
                }
            }
        }
    } else {
        NSLog(@"%@", error);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top