获取文件夹大小
/// 遍历文件夹获取目录下的所有的文件 遍历计算大小
class func folderSizeAtPath(folderPath:String) -> CGFloat {
if folderPath.count == 0 {
return 0
}
guard isExist(atPath: folderPath) else {
return 0
}
var fileSize:CGFloat = 0.0
do {
let files = try FileManager.default.contentsOfDirectory(atPath: folderPath)
for file in files {
let path = getDocumentPath() + "/\(file)"
fileSize = fileSize + getFileSize(atPath: path)
}
} catch {
}
return fileSize/(1000.0*1000.0)
}
获取单个文件大小
/// 获取单个文件的大小
class func getFileSize(atPath filePath : String) -> CGFloat {
guard isExist(atPath: filePath) else {
return 0
}
guard let dict = try? FileManager.default.attributesOfItem(atPath: filePath) as NSDictionary else {
return 0
}
return CGFloat(dict.fileSize())
}
清除缓存
class func clearWebCache(){
// MARK: - 清空缓存
let dateFrom: NSDate = NSDate.init(timeIntervalSince1970: 0)
if #available(iOS 9.0, *) {
let websiteDataTypes: NSSet = WKWebsiteDataStore.allWebsiteDataTypes() as NSSet
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: dateFrom as Date) {
MYLog("清空缓存完成")
}
} else {
let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
let cookiesFolderPath = libraryPath.appending("/Cookies")
try? FileManager.default.removeItem(atPath: cookiesFolderPath)
}
let htmlFolder = "\(nk_documentPath)/Html"
NK_FileUtils.deleteFolderItems(basePath: htmlFolder, exceptFolderName:"") { (finish) in
}
}
删除沙盒里的文件
//删除文件夹
class func deleteFolderItems(basePath:String, exceptFolderName:String, callBack: @escaping (Bool) -> Void) {
let fileManager = FileManager.default
let queue = DispatchQueue(label: "clearnQueue", attributes: [])
queue.async { () -> Void in
guard let childFiles = fileManager.subpaths(atPath: basePath) else{
callBack(true)
return
}
for fileName in childFiles {
if exceptFolderName != "" {
let folderName = fileName.components(separatedBy: "/").first
if folderName == exceptFolderName{
continue
}
}
let path = basePath as NSString
let fileFullPath = path.appendingPathComponent(fileName)
if fileManager.fileExists(atPath: fileFullPath) {
do {
try fileManager.removeItem(atPath: fileFullPath)
} catch _{}
}
}
DispatchQueue.main.async(execute: {
callBack(true)
})
}
}
读取本地文件
static func readLocalData(name: String, type:String) -> Any? {
//读取本地的文件
guard let path = Bundle.main.path(forResource: name, ofType: type) else{
return ""
}
let url = URL(fileURLWithPath: path)
// 带throws的方法需要抛异常
do {
let data = try Data(contentsOf: url)
let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
return jsonData
} catch let error as Error? {
return error?.localizedDescription
}
}
网友评论