swift -> clear cache and get cache size

 

 

    *** Empty the cache 

 

 

   //Clear Library/Caches
    func clearCaches(){
        do {
            try deleteLibraryFolderContents(folder: "Caches")
            //print("clear done")
        } catch {
            //print("clear Caches Error")
        }
    }
    
    
    
    //
    private func deleteLibraryFolderContents(folder: String) throws {
        let manager = FileManager.default
        let library = manager.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask)[0]
        let dir = library.appendingPathComponent(folder)
        let contents = try manager.contentsOfDirectory(atPath: dir.path)
        for content in contents {
            // if it is a snapshot, continue
            if(content == "Snapshots"){continue;}
            do {
                try manager.removeItem(at: dir.appendingPathComponent(content))
                //print("remove cache success:"+content)
            } catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) {
                //print("remove cache error:"+content)
                // "EPERM: operation is not permitted". We ignore this.
                #if DEBUG
                    //print("Couldn't delete some library contents.")
                #endif
            }
        }
    }
 

 

 

 

 

** Statistics cache size

    var fileSize:Int = 0;
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(false)
        UIView.animate(withDuration: 0.3, animations: {() -> Void in
            self.v.frame.origin.y = 0;
        }){(finished) -> Void in
            
            DispatchQueue.global().async {
                self.fileSize  = self.fileSizeOfCache();
                // get data asynchronously
                DispatchQueue.main.async {
                    //Modify the main thread UI
                    self.clearLable.text = "已用 "+String(self.fileSize)+" MB";
                }
            }
        }

        
        
    }

 

    //get cache size
    func fileSizeOfCache()-> Int {
        
        / / Take out the cache folder directory cache files are in this directory
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        //cache directory path
        //print(cachePath)
        
        // Get all the file arrays in the folder
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        
        //Quickly enumerate all file names to calculate file size
        var size = 0
        for file in fileArr! {
            
            // concatenate the filename to the path
            let path = cachePath?.appending("/\(file)")
            // Get file attributes
            let floder = try! FileManager.default.attributesOfItem(atPath: path!)
            // Get the file size attribute with a tuple
            for (abc, bcd) in floder {
                // Accumulate file size
                if abc == FileAttributeKey.size {
                    size += (bcd as AnyObject).integerValue
                }
            }
        }
        
        let mm = size / 1024 / 1024
        
        return mm
    }

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326125810&siteId=291194637