iOS Develops Cached Data in Clear Sandbox Path

Keywords: iOS Mobile network SQLite

Introduction:

When dealing with network resources, mobile applications usually do offline caching, among which picture caching is the most typical, and SDWebImage is the most popular offline caching framework.
However, offline caching will occupy the storage space of mobile phones, so the cache cleaning function has basically become the tagging function of App for information, shopping and reading.
Since the cached files are stored in App's sandbox, we can calculate the size of the cached files and delete the data through the NSFileManager API.

Let's first understand the sandbox mechanism:

Sandbox: The iOS system creates a file directory for each application, which is an independent, closed and secure space. A sandbox is a file directory. Sandbox specifies that a program can only operate in its own sandbox and cannot access the sandbox of other applications (iOS8 has partially opened access)

Sandbox: Used to store non-code files (pictures, audio, video, plist, SQLite database, text files, etc.)

Several paths commonly used in sandboxes:

Document folder:
ITunes automatically backs up the directory for persistent data that should be generated by the program's runtime. (Apple recommends that programs created and browsed in the program be stored here, and iTunes automatically includes the directory when backing up and replying.)
Acquisition method:

//File paths are arrays, where the first element is taken
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];`

Library folder:
Used to store default settings and other state information for programs, iTunes also backs up the directory automatically.
Acquisition method:

NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];

Library/Caches:
Used to store cached files, iTunes will not backup this directory, the files in this directory will not be deleted after the program exits, generally storing large but not very important files.
Acquisition method:

NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];

Library/Preferences: 
Used to store user preferences, iOS settings will find application settings in this directory, iTunes will automatically backup the directory, usually this folder is maintained by the system, it is recommended not to operate him.
The system does not have a way to get the folder path directly. It needs to get the Library path first and then do string splicing to find the path.

NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDoMainMask, YES)[0]; 
NSString*preferencePath = [libraryPath stringByAppendingString:@"/Preferences"];

Note: Instead of writing preferences directly to this folder, save and read preferences through NSUserDefaults.

tmp:
Save the temporary folder of the application and delete the corresponding files from the directory after use. If space is not enough, the system may delete the files in the directory. iTunes will not synchronize the folder. When the iPhone restarts, the files in the directory will be deleted.
Different from other methods, this path has its own methods:

NSString *tmpPath = NSTemporaryDirectory();
Let's go directly to the code below:

We can encapsulate it as a tool class: ClearCacheTool class.

ClearCacheTool.h file:

#import <Foundation/Foundation.h>

@interface ClearCacheTool : NSObject

/*s*
 *  Get the size of the folder under the path path path
 *
 *  @param path The folder path to get
 *
 *  @return Size of folders under path path return
 */
+ (NSString *)getCacheSizeWithFilePath:(NSString *)path;

/**
 *  Clear the cache of folders under path path path
 *
 *  @param path  To clear the cached folder path
 *
 *  @return Whether Clearance is Successful
 */
+ (BOOL)clearCacheWithFilePath:(NSString *)path;

ClearCacheTool.m file:

#import "ClearCacheTool.h"

@implementation ClearCacheTool

#pragma mark - Gets folder size under path path path
+ (NSString *)getCacheSizeWithFilePath:(NSString *)path{

    // Get all files under the "path" folder
    NSArray *subPathArr = [[NSFileManager defaultManager] subpathsAtPath:path];

    NSString *filePath  = nil;
    NSInteger totleSize = 0;

    for (NSString *subPath in subPathArr){

        // 1. Full Path of Stitching Each Document
        filePath =[path stringByAppendingPathComponent:subPath];
        // 2. Is it a folder, not by default?
        BOOL isDirectory = NO;
        // 3. Judging whether a document exists
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];

        // 4. The purpose of the above judgment is to ignore files that do not require calculation.
        if (!isExist || isDirectory || [filePath containsString:@".DS"]){
            // Filtration: 1. Folder does not exist 2. Filtration folder 3. Hidden files
            continue;
        }

        // 5. Specify the path to get the attributes of the path
        NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        /**
         attributesOfItemAtPath: Folder Path
         This method can only get the attributes of files, but can not get the attributes of folders, so it is also the reason why we need to traverse every file of folders.
         */

        // 6. Get the size of each file
        NSInteger size = [dict[@"NSFileSize"] integerValue];

        // 7. Calculate the total size
        totleSize += size;
    }

    //8. Convert folder size to M/KB/B
    NSString *totleStr = nil;

    if (totleSize > 1000 * 1000){
        totleStr = [NSString stringWithFormat:@"%.2fM",totleSize / 1000.00f /1000.00f];

    }else if (totleSize > 1000){
        totleStr = [NSString stringWithFormat:@"%.2fKB",totleSize / 1000.00f ];

    }else{
        totleStr = [NSString stringWithFormat:@"%.2fB",totleSize / 1.00f];
    }

    return totleStr;
}


#pragma mark - Clear cache size under path folder
+ (BOOL)clearCacheWithFilePath:(NSString *)path{

    //Subfolders to the next directory of the path path path
    NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];

    NSString *filePath = nil;

    NSError *error = nil;

    for (NSString *subPath in subPathArr)
    {
        filePath = [path stringByAppendingPathComponent:subPath];

        //Delete subfolders
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (error) {
            return NO;
        }
    }
    return YES;
}

When you use it, you just need to pass in the path!!!


The source code download address corresponding to this article: ClearCacheDemo

Posted by Toshiba23 on Thu, 28 Mar 2019 17:57:27 -0700