swift3.0网络图片缓存原理简析

2020-01-21 01:16:34于丽

3. 读写磁盘文件

(1)存储的时候给url进行md5加密得到fileName.md5文件名称,然后存储,如上面的截图

(2)读取文件时,给url进行md5加密得到path.md5的,然后获取文件数据


/* 写文件 
  fileName: 文件名称 
  data: 数据data 
*/ 
func writeFile(_ fileName:String , _ data:NSData) -> Bool{ 
   
  //let filePath:String = NSHomeDirectory() + "/Documents/" + fileName.md5 
  //return data.write(toFile: filePath, atomically: true) 
  guard self.isExistFileDir(ljFilePath) else{ 
    return false 
  } 
   
  guard let filePath : String = ljFilePath + fileName.md5 else{ 
    return false 
  } 
  return data.write(toFile: filePath, atomically: true) 
} 
 
//读取文件 -(根据路径) 
func readFileFromCache(_ path:String) -> NSData?{ 
   
  if self.isExistFileDir(ljFilePath) 
  { 
    let ljpatch = ljFilePath + path.md5 
    var result:NSData? 
    do{ 
      result = try NSData(contentsOfFile: ljpatch, options: Data.ReadingOptions.uncached) 
    }catch{ 
      return nil 
    } 
    return result 
  } 
  return nil 
} 

4.读写内存文件


import Foundation 
 
class LJCacheDataManage: NSObject{ 
   
  //单例 
  public static let shared = LJCacheDataManage() 
   
  // public var diskCache = 
   
  //缓存的数据 
  public var memoryCache = Dictionary<String, Data>() 
   
  //返回缓存的数据 
  func getMemoryCache(_ urlStr : String) -> Data? { 
     
    print("返回缓存的数据------(memoryCache[urlStr] ?? nil)") 
    return (memoryCache[urlStr] ?? nil) 
  } 
   
  //设置缓存值 
  func setMemoryCache(_ urlStr : String, _ data : Data){ 
    if urlStr != "", data != nil { 
      memoryCache[urlStr] = data 
    } 
  } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到IOS开发频道。