0

I have an App in which I record the sound files and store it in apps Document Directory.

What I want is, it should contain only yesterday and to days older files and remove all others from the folder in iPhone app. Is there any way to do this?

Thanks ..

rohan-patel
  • 5,772
  • 5
  • 45
  • 68

4 Answers4

7

Please look at the following code.

//Get the Document directory path.
 #define kDOCSFOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

//Delete files by iterating items of the folder.
NSFileManager* fm = [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator* en = [fm enumeratorAtPath:kDOCSFOLDER];    
NSError* err = nil;
BOOL res;

NSString* file;
while (file = [en nextObject]) {
            // Date comparison.
    NSDate   *creationDate = [[fm attributesOfItemAtPath:file error:nil] fileCreationDate];
    NSDate *yesterDay = [[NSDate date] dateByAddingTimeInterval:(-1*24*60*60)];

    if ([creationDate compare:yesterDay] == NSOrderedAscending)
    {
        // creation date is before the Yesterday date
        res = [fm removeItemAtPath:[kDOCSFOLDER stringByAppendingPathComponent:file] error:&err];

        if (!res && err) {
            NSLog(@"oops: %@", err);
        }

    }

}
Vignesh
  • 10,205
  • 2
  • 35
  • 73
2

If you would have searched little you would have got this:

 [fileManager removeItemAtPath: fullPath error:NULL];

So you can get creation date of your file using something like this:

NSFileManager* fileManager = [NSFileManager defaultManager];
NSDictionary* dict = [fileManager attributesOfItemAtPath:filePath error:nil];
NSDate *date = (NSDate*)[dict objectForKey: NSFileCreationDate];

Compare those date in if condition and delete those files.

UPDATE 1: Working code to delete files which are older than two days.

// 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:-2*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];
        }
    }
}
rohan-patel
  • 5,772
  • 5
  • 45
  • 68
1

Please check following code for swift :

func cleanUp() {
    let maximumDays = 2.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 files: \(error)")
    }
}
0

Please check following code:

NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] error:nil];
for (NSString *file in dirContents) {
    NSError *error= nil;
    NSDictionary *dictAtt = [[NSFileManager defaultManager] attributesOfItemAtPath:/*file path*/ error:&error];

    NSDate *d =[[NSDate date] dateByAddingTimeInterval:-86400];
    if ([[dictAtt valueForKey:NSFileCreationDate] compare:d] == NSOrderedAscending) {
        [[NSFileManager defaultManager] removeItemAtPath:/*file path*/ error:&error];
    }
}
priyanka
  • 2,076
  • 1
  • 16
  • 20