Clear cache for iOS and cache for ios
// Click the clear cache button
-(Void) putBufferBtnClicked :( UIButton *) btn {
CGFloat size = [self folderSizeAtPath: NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ). lastObject] + [self folderSizeAtPath: NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES ). lastObject] + [self folderSizeAtPath: NSTemporaryDirectory ()];
NSString * message = size> 1? [NSString stringWithFormat: @ "cache %. 2fM, delete cache", size]: [NSString stringWithFormat: @ "cache %. 2fK, delete cache", size * 1024.0];
UIAlertController * alert = [UIAlertController alertControllerWithTitle: nil message: message preferredStyle :( UIAlertControllerStyleAlert)];
UIAlertAction * action = [UIAlertAction actionWithTitle: @ "OK" style :( UIAlertActionStyleDefault) handler: ^ (UIAlertAction * action) {[self cleanCaches];}];
UIAlertAction * cancel = [UIAlertAction actionWithTitle: @ "cancel" style :( UIAlertActionStyleCancel) handler: nil];
[Alert addAction: action];
[Alert addAction: cancel];
[Self showDetailViewController: alert sender: nil];
}
// Calculate the directory size
-(CGFloat) folderSizeAtPath :( NSString *) path {
// Use NSFileManager to manage files
NSFileManager * manager = [NSFileManager defamanager manager];
CGFloat size = 0;
If ([manager fileExistsAtPath: path]) {
// Obtain the file in the directory and calculate its size
NSArray * childrenFile = [manager subpathsAtPath: path];
For (NSString * fileName in childrenFile ){
NSString * absolutePath = [path stringByAppendingPathComponent: fileName];
Size + = [manager attributesOfItemAtPath: absolutePath error: nil]. fileSize;
}
// Convert the size to M
Return size/1024.0/1024.0;
}
Return 0;
}
// Delete an object based on the path
-(Void) cleanCaches :( NSString *) path {
// Use NSFileManager to manage files
NSFileManager * fileManager = [NSFileManager defaultManager];
If ([fileManager fileExistsAtPath: path]) {
// Get the file name under this path
NSArray * childrenFiles = [fileManager subpathsAtPath: path];
For (NSString * fileName in childrenFiles ){
// Splicing path
NSString * absolutePath = [path stringByAppendingPathComponent: fileName];
// Delete the object
[FileManager removeItemAtPath: absolutePath error: nil];
}
}
}
// Example of calculating the file size in the sandbox and deleting the file in the sandbox:
-(Void) cleanCaches {
[Self cleanCaches: NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES). firstObject];
[Self cleanCaches: NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES). firstObject];
[Self cleanCaches: NSTemporaryDirectory ()];
}