IOS development-implement the cache cleanup function and clear cache for ios development
Mobile applications generally perform offline cache processing when processing network resources. The image cache is the most typical one. The popular offline cache framework is SDWebImage.
However, the offline cache occupies the storage space of the mobile phone. Therefore, the cache cleanup function is a standard function for information, shopping, and reading apps.
The implementation of the offline cache function introduced today is mainly divided into the acquisition and deletion of cache files.
Obtain the cache file size.
Because cached files exist in the sandbox, we can use the NSFileManager API to calculate the cached file size.
Calculate the size of a single file
+(float)fileSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; if([fileManager fileExistsAtPath:path]){ long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize; return size/1024.0/1024.0; } return 0;}
Calculate directory size
+ (Float) folderSizeAtPath :( NSString *) path {NSFileManager * fileManager = [NSFileManager defaultManager]; float folderSize; if ([fileManager fileExistsAtPath: path]) {NSArray * childerFiles = [fileManager subpathsAtPath: path]; for (NSString * fileName in childerFiles) {NSString * absolutePath = [path paths: fileName]; folderSize + = [FileService fileSizeAtPath: absolutePath];}
// Implementation of the SDK webimage Framework's own computing cache folderSize + = [[SDImageCache nvidimagecache] getSize]/1024.0/1024.0; return folderSize;} return 0 ;}
Effect:
Clear cached files
The NSFileManager API is also used for file operations. The SDWebImage framework implements the cache cleanup operation, which can be called directly.
+ (Void) receivache :( NSString *) path {NSFileManager * fileManager = [NSFileManager defaultManager]; if ([fileManager fileExistsAtPath: path]) {NSArray * childerFiles = [fileManager subpathsAtPath: path]; for (NSString * fileName in childerFiles) {// if necessary, add conditions to filter out NSString * absolutePath = [path stringByAppendingPathComponent: fileName]; [fileManager removeItemAtPath: absolutePath error: nil] ;}} [[SDImageCache nvidimagecache] cleanDisk];}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.