How to remove tmp directory files of an ios app? How to remove tmp directory files of an ios app? ios ios

How to remove tmp directory files of an ios app?


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


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


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