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

发布于 2025-01-03 16:19:00 字数 140 浏览 4 评论 0原文

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

有什么方法可以删除所有这些捕获,或者有什么方法可以轻松清理所有缓存和临时文件?

I'm working on an app that uses the iPhone camera and after making several tests I've realised that it is storing all the captured videos on the tmp directory of the app.
The captures don`t disappear even if the phone is restarted.

Is there any way to remove all these captures or is there any way to easily clean all cache and temp files?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

小鸟爱天空丶 2025-01-10 16:19:00

是的。这个方法效果很好:

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

Yes. This method works well:

+ (void)clearTmpDirectory
{
    NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
    for (NSString *file in tmpDirectory) {
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
    }
}
丿*梦醉红颜 2025-01-10 16:19:00

Swift 3 版本作为扩展:

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

使用示例:

FileManager.default.clearTmpDirectory()

感谢 Max Maier,Swift 2 版本:

func clearTmpDirectory() {
    do {
        let tmpDirectory = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(NSTemporaryDirectory())
        try tmpDirectory.forEach { file in
            let path = String.init(format: "%@%@", NSTemporaryDirectory(), file)
            try NSFileManager.defaultManager().removeItemAtPath(path)
        }
    } catch {
        print(error)
    }
}

Swift 3 version as extension:

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

Example of usage:

FileManager.default.clearTmpDirectory()

Thanks to Max Maier, Swift 2 version:

func clearTmpDirectory() {
    do {
        let tmpDirectory = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(NSTemporaryDirectory())
        try tmpDirectory.forEach { file in
            let path = String.init(format: "%@%@", NSTemporaryDirectory(), file)
            try NSFileManager.defaultManager().removeItemAtPath(path)
        }
    } catch {
        print(error)
    }
}
傾城如夢未必闌珊 2025-01-10 16:19:00

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

Swift 4

One of the possible implementations

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
        }
    }
}
汹涌人海 2025-01-10 16:19:00

感谢马克斯·迈尔和罗曼·巴尔兹扎克。更新到 Swift 3,使用 URL 而不是字符串。

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

Thanks to Max Maier and Roman Barzyczak. Updated to Swift 3, using URLs instead of strings.

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")
        }
}
没企图 2025-01-10 16:19:00

尝试使用此代码删除 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;
}

Try this code to remove NSTemporaryDirectory files

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

and to check data remove or not write code in 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;
}
爱格式化 2025-01-10 16:19:00

我知道我迟到了,但我想放弃直接在 URL 上运行的实现:

let fileManager = FileManager.default
let temporaryDirectory = fileManager.temporaryDirectory
try? fileManager
    .contentsOfDirectory(at: temporaryDirectory, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants)
    .forEach { file in
        try? fileManager.removeItem(atPath: file.path)
    }

I know i'm late to the party but i'd like to drop my implementation which works straight on URLs, too:

let fileManager = FileManager.default
let temporaryDirectory = fileManager.temporaryDirectory
try? fileManager
    .contentsOfDirectory(at: temporaryDirectory, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants)
    .forEach { file in
        try? fileManager.removeItem(atPath: file.path)
    }
原来分手还会想你 2025-01-10 16:19:00

这适用于越狱的 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]);
        }
    }
}

This works on a jailbroken iPad, but I think this should work on a non-jailbroken device also.

-(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]);
        }
    }
}
愁杀 2025-01-10 16:19:00
//
//  FileManager+removeContentsOfTemporaryDirectory.swift
//
//  Created by _ _ on _._.202_.
//  Copyright © 202_ _ _. All rights reserved.
//

import Foundation

public extension FileManager {

    /// Perform this method on a background thread.
    /// Returns `true` if :
    ///     * all temporary folder files have been deleted.
    ///     * the temporary folder is empty.
    /// Returns `false` if :
    ///     * some temporary folder files have not been deleted.
    /// Error handling:
    ///     * Throws `contentsOfDirectory` directory access error.
    ///     * Ignores single file `removeItem` errors.
    ///
    @discardableResult
    func removeContentsOfTemporaryDirectory() throws -> Bool  {
        
        if Thread.isMainThread {
            let mainThreadWarningMessage = "\(#file) - \(#function) executed on main thread. Do not block the main thread."
            assertionFailure(mainThreadWarningMessage)
        }
        
        do {
            
            let tmpDirURL = FileManager.default.temporaryDirectory
            let tmpDirectoryContent = try contentsOfDirectory(atPath: tmpDirURL.path)
            
            guard tmpDirectoryContent.count != 0 else { return true }
            
            for tmpFilePath in tmpDirectoryContent {
                let trashFileURL = tmpDirURL.appendingPathComponent(tmpFilePath)
                try removeItem(atPath: trashFileURL.path)
            }
            
            let tmpDirectoryContentAfterDeletion = try contentsOfDirectory(atPath: tmpDirURL.path)
            
            return tmpDirectoryContentAfterDeletion.count == 0
            
        } catch let directoryAccessError {
            throw directoryAccessError
        }
        
    }
}
//
//  FileManager+removeContentsOfTemporaryDirectory.swift
//
//  Created by _ _ on _._.202_.
//  Copyright © 202_ _ _. All rights reserved.
//

import Foundation

public extension FileManager {

    /// Perform this method on a background thread.
    /// Returns `true` if :
    ///     * all temporary folder files have been deleted.
    ///     * the temporary folder is empty.
    /// Returns `false` if :
    ///     * some temporary folder files have not been deleted.
    /// Error handling:
    ///     * Throws `contentsOfDirectory` directory access error.
    ///     * Ignores single file `removeItem` errors.
    ///
    @discardableResult
    func removeContentsOfTemporaryDirectory() throws -> Bool  {
        
        if Thread.isMainThread {
            let mainThreadWarningMessage = "\(#file) - \(#function) executed on main thread. Do not block the main thread."
            assertionFailure(mainThreadWarningMessage)
        }
        
        do {
            
            let tmpDirURL = FileManager.default.temporaryDirectory
            let tmpDirectoryContent = try contentsOfDirectory(atPath: tmpDirURL.path)
            
            guard tmpDirectoryContent.count != 0 else { return true }
            
            for tmpFilePath in tmpDirectoryContent {
                let trashFileURL = tmpDirURL.appendingPathComponent(tmpFilePath)
                try removeItem(atPath: trashFileURL.path)
            }
            
            let tmpDirectoryContentAfterDeletion = try contentsOfDirectory(atPath: tmpDirURL.path)
            
            return tmpDirectoryContentAfterDeletion.count == 0
            
        } catch let directoryAccessError {
            throw directoryAccessError
        }
        
    }
}
找个人就嫁了吧 2025-01-10 16:19:00

使用此专用代码删除所有 tmp 文件:

let directory = FileManager.default.temporaryDirectory
try contentsOfDirectory(at: directory, includingPropertiesForKeys: []).forEach(removeItem)

如果需要,可以在执行 forEach 之前过滤内容

Use this dedicated code to remove all tmp files:

let directory = FileManager.default.temporaryDirectory
try contentsOfDirectory(at: directory, includingPropertiesForKeys: []).forEach(removeItem)

You filter the contents before performing the forEach if you need

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文