Swift之缓存文件处理
【摘要】
//
// YDWCache.swift
// Project
//
// Created by cptech on 2017/6/19.
// Copyright © 2017年 CPTECH_...
//
// YDWCache.swift
// Project
//
// Created by cptech on 2017/6/19.
// Copyright © 2017年 CPTECH_ydw. All rights reserved.
//
import UIKit
class YDWCache: NSObject {
/**
* 以NSHomeDirectory()为例
*/
// 读取缓存的大小
static func returnCacheSize()->String {
return String(format:"%.2f",forderSizeAtPath(folderPath: NSHomeDirectory()))
}
// 根据文件的路径计算文件的大小(MB)
static func returnFileSize(path:String)->Double {
let fileManager = FileManager.default
var fileSize:Double = 0
do {
fileSize = Double(try fileManager.attributesOfItem(atPath: path)[FileAttributeKey.size] as! UInt64)
fileSize = Double((try fileManager.attributesOfItem(atPath: path) as NSDictionary).fileSize())
} catch {
dump(error)
}
return fileSize/1024.0/1024.0
}
// 遍历文件的子目录,计算文件的大小
static func forderSizeAtPath(folderPath:String)->Double {
let filemanager = FileManager.default
if !filemanager.fileExists(atPath: folderPath) {
return 0
}
let childFilePath = filemanager.subpaths(atPath: folderPath)
var fileSize:Double = 0
for path in childFilePath! {
let fileAbsoluePath = folderPath+"/"+path
fileSize += YDWCache.returnFileSize(path: fileAbsoluePath)
}
return fileSize
}
// 清除缓存
static func cleanCache(competion:()->Void) {
YDWCache.deleteFolder(folderPath: NSHomeDirectory() + "/Documents")
YDWCache.deleteFolder(folderPath: NSHomeDirectory() + "/Library")
YDWCache.deleteFolder(folderPath: NSHomeDirectory() + "/tmp")
competion()
}
// 删除单个文件
static func deleteFile(path:String) {
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: path)
} catch {
dump(error)
}
}
// 删除文件下的所有文件
static func deleteFolder(folderPath:String) {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: folderPath) {
}
let childFilePath = fileManager.subpaths(atPath: folderPath)
for path in childFilePath! {
let fileAbsoluePath = folderPath+"/"+path
YDWCache.deleteFile(path: fileAbsoluePath)
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
文章来源: blog.csdn.net,作者:Serendipity·y,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/Forever_wj/article/details/73467453
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)