Max*_*ier 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];
}
}
Run Code Online (Sandbox Code Playgroud)
Rom*_*zak 22
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
FileManager.default.clearTmpDirectory()
Run Code Online (Sandbox Code Playgroud)
感谢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)
}
}
Run Code Online (Sandbox Code Playgroud)
Vya*_*lav 13
斯威夫特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
}
}
}
Run Code Online (Sandbox Code Playgroud)
感谢马克斯·迈尔和罗曼·巴尔兹扎克。更新到 Swift 3,使用 URL 而不是字符串。
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")
}
}
Run Code Online (Sandbox Code Playgroud)
这适用于越狱的 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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)