如何从iPhone的文档目录中删除超过两天的文件

时间:2012-04-09 11:05:26

标签: iphone

我有一个应用程序,我在其中记录声音文件并将其存储在应用程序文档目录中。

我想要的是,它应该只包含昨天和几天的旧文件,并从iPhone应用程序中的文件夹中删除所有其他文件。有没有办法做到这一点?

谢谢..

4 个答案:

答案 0 :(得分:7)

请查看以下代码。

//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);
        }

    }

}

答案 1 :(得分:2)

如果你搜索的很少,你会得到这个:

 [fileManager removeItemAtPath: fullPath error:NULL];

因此,您可以使用以下内容获取文件的创建日期:

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

比较if条件中的日期并删除这些文件。

  

更新1:使用代码删除超过两天的文件。

// 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];
        }
    }
}

答案 2 :(得分:1)

请迅速检查以下代码:

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)")
    }
}

答案 3 :(得分:0)

请检查以下代码:

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];
    }
}