iOS开发

前言:

开发移动应用时,请求网络资源是再常见不过的功能。如果每次都去请求,不但浪费时间,用户体验也会变差,所以移动应用都会做离线缓存处理,其中已图片缓存最为常见。
但是时间长了,离线缓存会占用大量的手机空间,所以清除缓存功能基本是移动应用开发的标配。


实现:

本文介绍在iOS开发中,Swift实现清除缓存功能。主要分为统计缓存文件大小和删除缓存文件两个步骤:

1.统计缓存文件大小

func fileSizeOfCache()-> Int {

    // 取出cache文件夹目录 缓存文件都在这个目录下
    let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
    //缓存目录路径
    print(cachePath)

    // 取出文件夹下所有文件数组
    let fileArr = NSFileManager.defaultManager().subpathsAtPath(cachePath!)

    //快速枚举出所有文件名 计算文件大小
    var size = 0
    for file in fileArr! {

        // 把文件名拼接到路径中
        let path = cachePath?.stringByAppendingString("/(file)")
        // 取出文件属性
        let floder = try! NSFileManager.defaultManager().attributesOfItemAtPath(path!)
        // 用元组取出文件大小属性
        for (abc, bcd) in floder {
            // 累加文件大小
            if abc == NSFileSize {
                size += bcd.integerValue
            }
        }
    }

    let mm = size / 1024 / 1024

    return mm
}

2.删除缓存文件

func clearCache() {

    // 取出cache文件夹目录 缓存文件都在这个目录下
    let cachePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first

    // 取出文件夹下所有文件数组
    let fileArr = NSFileManager.defaultManager().subpathsAtPath(cachePath!)

    // 遍历删除
    for file in fileArr! {

        let path = cachePath?.stringByAppendingString("/(file)")
        if NSFileManager.defaultManager().fileExistsAtPath(path!) {

            do {
                try NSFileManager.defaultManager().removeItemAtPath(path!)
            } catch {

            }
        }
    }
}

3.效果图

清除缓存01.gif

本文首发于马燕龙个人博客,欢迎分享,转载请标明出处。
马燕龙个人博客:http://www.mayanlong.com
马燕龙个人微博:http://weibo.com/imayanlong 
马燕龙Github主页:https://github.com/yanlongma

原文地址:https://www.cnblogs.com/imayanlong/p/5617625.html