Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - How to selectively delete files older than a month in Documents Directory

I am downloading images to my app which after a few weeks the user will not care about. I download them to the app so they will not have to be downloaded every launch. The problem is I do not want the Documents folder to get bigger than it has to over time. So I thought I could "clean up" file older than a Month.

The problem is, there will be a few files in there that WILL be older than a month but that I do NOT want to delete. They will be Static Named files so they will be easy to identify and there will only be 3 or 4 of them. While there might be a few dozen old files I want to delete. So heres an example:

picture.jpg           <--Older than a month DELETE
picture2.jpg          <--NOT older than a month Do Not Delete
picture3.jpg          <--Older than a month DELETE
picture4.jpg          <--Older than a month DELETE
keepAtAllTimes.jpg    <--Do not delete no matter how old
keepAtAllTimes2.jpg   <--Do not delete no matter how old
keepAtAllTimes3.jpg   <--Do not delete no matter how old

How could I selectively delete these files?

Thanks in advance!

like image 423
Louie Avatar asked Apr 12 '12 17:04

Louie


People also ask

How do you delete files from older than 30 days?

Open Start on Windows 10. Search for Command Prompt, right-click the result and select the Run as administrator option. In the command, change "C:\path\to\folder" specifying the path to the folder you want to delete files and change /d -30 to select files with a last modified date.

How do I mass delete iPhone files?

Touch and hold the file or folder, then choose an option: Copy, Duplicate, Move, Delete, Rename, or Compress. To modify multiple files or folders at the same time, tap Select, tap your selections, then tap an option at the bottom of the screen.

How do I delete old documents?

Locate the file that you want to delete. Right-click the file, then click Delete on the shortcut menu. Tip: You can also select more than one file to be deleted at the same time. Press and hold the CTRL key as you select multiple files to delete.


3 Answers

Code to delete files which are older than two days. Originally I answered here. I tested it and it was working in my project.

P.S. Be cautious before you delete all files in Document directory because doing so you might end up losing your Database file(If you are using..!!) there which may cause trouble for your Application. Thats why I have kept if condition there. :-))

// Code to delete images older than two days.
   #define kDOCSFOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

NSFileManager* fileManager = [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator* en = [fileManager enumeratorAtPath:kDOCSFOLDER];    

NSString* file;
while (file = [en nextObject])
{
    NSLog(@"File To Delete : %@",file);
    NSError *error= nil;

    NSString *filepath=[NSString stringWithFormat:[kDOCSFOLDER stringByAppendingString:@"/%@"],file];


    NSDate   *creationDate =[[fileManager attributesOfItemAtPath:filepath error:nil] fileCreationDate];
    NSDate *d =[[NSDate date] dateByAddingTimeInterval:-1*24*60*60];

    NSDateFormatter *df=[[NSDateFormatter alloc]init];// = [NSDateFormatter initWithDateFormat:@"yyyy-MM-dd"];
    [df setDateFormat:@"EEEE d"]; 

    NSString *createdDate = [df stringFromDate:creationDate];

     NSString *twoDaysOld = [df stringFromDate:d];

    NSLog(@"create Date----->%@, two days before date ----> %@", createdDate, twoDaysOld);

    // if ([[dictAtt valueForKey:NSFileCreationDate] compare:d] == NSOrderedAscending)
    if ([creationDate compare:d] == NSOrderedAscending)

    {
        if([file isEqualToString:@"RDRProject.sqlite"])
        {

            NSLog(@"Imp Do not delete");
        }

        else
        {
             [[NSFileManager defaultManager] removeItemAtPath:[kDOCSFOLDER stringByAppendingPathComponent:file] error:&error];
        }
    }
}
like image 121
rohan-patel Avatar answered Oct 12 '22 23:10

rohan-patel


You can get the file creation date, look at this SO Post and then just compare the dates. and create two different arrays for files needs to be deleted and non to be deleted..

like image 26
k-thorat Avatar answered Oct 13 '22 01:10

k-thorat


My two cents worth. Change meetsRequirement to suit.

func cleanUp() {
    let maximumDays = 10.0
    let minimumDate = Date().addingTimeInterval(-maximumDays*24*60*60)
    func meetsRequirement(date: Date) -> Bool { return date < minimumDate }

    func meetsRequirement(name: String) -> Bool { return name.hasPrefix(applicationName) && name.hasSuffix("log") }

    do {
        let manager = FileManager.default
        let documentDirUrl = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        if manager.changeCurrentDirectoryPath(documentDirUrl.path) {
            for file in try manager.contentsOfDirectory(atPath: ".") {
                let creationDate = try manager.attributesOfItem(atPath: file)[FileAttributeKey.creationDate] as! Date
                if meetsRequirement(name: file) && meetsRequirement(date: creationDate) {
                    try manager.removeItem(atPath: file)
                }
            }
        }
    }
    catch {
        print("Cannot cleanup the old files: \(error)")
    }
}
like image 22
Verticon Avatar answered Oct 13 '22 00:10

Verticon