Подтвердить что ты не робот

Как удалить файлы каталога tmp приложения ios?

Я работаю над приложением, которое использует камеру iPhone, и после нескольких тестов я понял, что он хранит все захваченные видео в каталоге tmp приложения. Захваты не исчезают, даже если телефон перезагружен.

Есть ли способ удалить все эти захваты или есть ли способ легко очистить все файлы кэша и временных файлов?

4b9b3361

Ответ 1

Да. Этот метод работает хорошо:

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

Ответ 2

Версия 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()

Благодаря Макс Майер, версия 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)
    }
}

Ответ 3

Это работает на взломанном iPad, но я думаю, что это тоже должно работать на не-jailbroken устройстве.

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

Ответ 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;
}

Ответ 5

Благодаря Максу Майеру и Роману Барзичаку. Обновлен до 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")
        }
}

Ответ 6

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