Iphone iOS-如何有选择地删除文档目录中早于一个月的文件

Iphone iOS-如何有选择地删除文档目录中早于一个月的文件,iphone,objective-c,ios,iphone-4,Iphone,Objective C,Ios,Iphone 4,我正在将图像下载到我的应用程序中,几周后用户将不再关心这些图像。我将它们下载到应用程序中,这样就不必每次发布都下载它们。问题是我不希望文档文件夹随着时间的推移变得比它必须的更大。所以我想我可以“清理”一个月前的文件 问题是,那里会有一些文件超过一个月,但我不想删除。它们将是静态命名文件,因此易于识别,并且只有3或4个文件。虽然可能有几十个旧文件我想删除。下面是一个例子: picture.jpg <--Older than a month DELETE picture2.

我正在将图像下载到我的应用程序中,几周后用户将不再关心这些图像。我将它们下载到应用程序中,这样就不必每次发布都下载它们。问题是我不希望文档文件夹随着时间的推移变得比它必须的更大。所以我想我可以“清理”一个月前的文件

问题是,那里会有一些文件超过一个月,但我不想删除。它们将是静态命名文件,因此易于识别,并且只有3或4个文件。虽然可能有几十个旧文件我想删除。下面是一个例子:

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

picture.jpg你可以得到文件创建日期,看看这个,然后比较日期。并为需要删除的文件和不需要删除的文件创建两个不同的数组

要查找文件的创建日期,您可以参考非常有用的StackOverflow帖子:

参考这篇文章,这可能会帮助你删除它们。您可以大致了解从文档目录中删除这些数据需要做什么:


希望这对您有所帮助。

删除超过两天的文件的代码。原来我回答。我测试了它,它在我的项目中工作

p.S.删除文档目录中的所有文件之前要小心,因为这样做可能会丢失数据库文件(如果您正在使用..!!),这可能会给您的应用程序带来麻烦。这就是为什么我在那里保留了if条件。:-)


这里有一个函数,它不使用日期字符串比较并在枚举器中预取修改时间:

+ (NSArray<NSURL *> *)deleteFilesOlderThan:(NSDate *)earliestDateAllowed
                               inDirectory:(NSURL *)directory {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator<NSURL *> *enumerator =
        [fileManager enumeratorAtURL:directory
            includingPropertiesForKeys:@[ NSURLContentModificationDateKey ]
                               options:0
                          errorHandler:^BOOL(NSURL *_Nonnull url, NSError *_Nonnull error) {
                              NSLog(@"Failed while enumerating directory '%@' for files to "
                                         @"delete: %@ (failed on file '%@')",
                                         directory.path, error.localizedDescription, url.path);
                              return YES;
                          }];

    NSURL *file;
    NSError *error;
    NSMutableArray<NSURL *> *filesDeleted = [NSMutableArray new];
    while (file = [enumerator nextObject]) {
        NSDate *mtime;
        if (![file getResourceValue:&mtime forKey:NSURLContentModificationDateKey error:&error]) {
            NSLog(@"Couldn't fetch mtime for file '%@': %@", file.path, error);
            continue;
        }

        if ([earliestDateAllowed earlierDate:mtime] == earliestDateAllowed) {
            continue;
        }

        if (![fileManager removeItemAtURL:file error:&error]) {
            NSLog(@"Couldn't delete file '%@': %@", file.path, error.localizedDescription);
            continue;
        }
        [filesDeleted addObject:file];
    }
    return filesDeleted;
}

在Swift 3和4中,删除文档目录中的特定文件

do{
    try FileManager.default.removeItem(atPath: theFile)
} catch let theError as Error{
    print("file not found \(theError)")
}

我的两分钱值。更改meetsRequirement以适应

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)")
    }
}
func cleanUp(){
设最大天数=10.0
设minimumDate=Date()。添加时间间隔(-maximumDays*24*60*60)
func meetsRequirement(日期:date)->Bool{返回日期<最小日期}
func meetsRequirement(名称:String)->Bool{return name.hasPrefix(applicationName)&&name.hasSuffix(“log”)}
做{
让manager=FileManager.default
让documentDirUrl=try manager.url(对于:.documentDirectory,在:.userDomainMask中,适用于:nil,创建:false)
if manager.changeCurrentDirectoryPath(documentDirUrl.path){
对于try manager.contentsof目录中的文件(路径:“.”){
让creationDate=尝试manager.attributesOfItem(atPath:file)[FileAttributeKey.creationDate]作为!日期
如果满足要求(名称:文件)和满足要求(日期:创建日期){
尝试manager.removietem(atPath:file)
}
}
}
}
抓住{
打印(“无法清理旧文件:\(错误)”)
}
}

+1表示正确答案。但是,与其使用链接问题中的解决方案,我建议使用
NSMetadataQuery
,它将自动搜索超过某个日期的文件。扫描目录,提取文件日期,然后删除超过一个月的文件。为那些您不想删除的文件创建一个要比较的文件列表。是。三天前也有人问过同样的问题。我最初试过,但没有成功。我又试了一次,现在可以用了。谢谢啊哈。。酷。。实际上,我试了几分钟来回答这个问题,并在我运行的应用程序中验证了它的有效性,然后我发布了代码。。您将在我的代码中看到日期验证的额外代码…:-)@巴特:但我自己回答了。我没有抄袭任何东西。@ParthBhatt:如果他们伤害了你,我会道歉。我将删除评论。谢谢。请注意,NSString有一个非常有用且安全的方法,名为stringByAppendingPathComponent
do{
    try FileManager.default.removeItem(atPath: theFile)
} catch let theError as Error{
    print("file not found \(theError)")
}
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)")
    }
}