如何删除ios应用程序的tmp目录文件?

时间:2012-02-08 15:37:36

标签: ios xcode file-io temp

我正在开发一款使用iPhone相机的应用程序,经过多次测试后,我意识到它将所有捕获的视频存储在应用程序的tmp目录中。 即使手机重新启动,捕获也不会消失。

有没有办法删除所有这些捕获,还是有办法轻松清理所有缓存和临时文件?

6 个答案:

答案 0 :(得分:45)

是。这种方法效果很好:

+ (void)clearTmpDirectory
{
    NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
    for (NSString *file in tmpDirectory) {
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
    }
}

答案 1 :(得分:22)

Swift 3版本作为扩展名:

StringBuilder stbuilder = new StringBuilder();

                foreach (var filePath in dlgFileOpen.FileNames)
                {
                    StreamReader sr = new StreamReader(filePath);
                    stbuilder.Append(sr.ReadToEnd());
                    sr.Close();

//Or Much faster you can use 
                    stbuilder.Append(File.ReadAllText(filePath));
                    stbuilder.Append(Environment.NewLine);


                    stbuilder.Append(Environment.NewLine);
                    txtFileContent.Text = stbuilder.ToString();
                }

使用示例:

extension FileManager {
    func clearTmpDirectory() {
        do {
            let tmpDirectory = try contentsOfDirectory(atPath: NSTemporaryDirectory())
            try tmpDirectory.forEach {[unowned self] file in
                let path = String.init(format: "%@%@", NSTemporaryDirectory(), file)
                try self.removeItem(atPath: path)
            }
        } catch {
            print(error)
        }
    }
}

感谢Max Maier,Swift 2版本:

FileManager.default.clearTmpDirectory()

答案 2 :(得分:9)

Swift 4

可能的实现之一

extension FileManager {
    func clearTmpDirectory() {
        do {
            let tmpDirURL = FileManager.default.temporaryDirectory
            let tmpDirectory = try contentsOfDirectory(atPath: tmpDirURL.path)
            try tmpDirectory.forEach { file in
                let fileUrl = tmpDirURL.appendingPathComponent(file)
                try removeItem(atPath: fileUrl.path)
            }
        } catch {
           //catch the error somehow
        }
    }
}

答案 3 :(得分:4)

尝试使用此代码删除NSTemporaryDirectory文件

-(void)deleteTempData
{
    NSString *tmpDirectory = NSTemporaryDirectory();
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:tmpDirectory error:&error];
    for (NSString *file in cacheFiles)
    {
        error = nil;
        [fileManager removeItemAtPath:[tmpDirectory stringByAppendingPathComponent:file] error:&error];
    }
}

并检查数据是否删除或不在didFinishLaunchingWithOptions中编写代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];

    NSString *tmpDirectory = NSTemporaryDirectory();
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:tmpDirectory error:&error];
    NSLog(@"TempFile Count ::%lu",(unsigned long)cacheFiles.count);

    return YES;
}

答案 4 :(得分:3)

这适用于越狱的iPad,但我认为这也适用于非越狱设备。

-(void) clearCache
{
    for(int i=0; i< 100;i++)
    {
        NSLog(@"warning CLEAR CACHE--------");
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError * error;
    NSArray * cacheFiles = [fileManager contentsOfDirectoryAtPath:NSTemporaryDirectory() error:&error];

    for(NSString * file in cacheFiles)
    {
        error=nil;
        NSString * filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:file ];
        NSLog(@"filePath to remove = %@",filePath);

        BOOL removed =[fileManager removeItemAtPath:filePath error:&error];
        if(removed ==NO)
        {
            NSLog(@"removed ==NO");
        }
        if(error)
        {
            NSLog(@"%@", [error description]);
        }
    }
}

答案 5 :(得分:3)

感谢Max Maier和Roman Barzyczak。更新为Swift 3,使用URL而不是字符串。

Swift 3

func clearTmpDir(){

        var removed: Int = 0
        do {
            let tmpDirURL = URL(string: NSTemporaryDirectory())!
            let tmpFiles = try FileManager.default.contentsOfDirectory(at: tmpDirURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
            print("\(tmpFiles.count) temporary files found")
            for url in tmpFiles {
                removed += 1
                try FileManager.default.removeItem(at: url)
            }
            print("\(removed) temporary files removed")
        } catch {
            print(error)
            print("\(removed) temporary files removed")
        }
}