-1

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

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

谢谢 ..

4

4 回答 4

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

    }

}
于 2012-04-09T11:21:59.633 回答
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];
        }
    }
}
于 2012-04-09T11:12:04.653 回答
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)")
    }
}
于 2019-09-14T10:34:30.460 回答
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];
    }
}
于 2012-04-09T11:42:22.880 回答