swift3.0 Data数据缓存write、read函数

1.Data数据写入write操作错误:
CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme

错误详情:```Error Domain=NSCocoaErrorDomain Code=518 "The file couldn’t be saved because the specified URL type isn’t supported." UserInfo={NSURL=/Users/tj-ios/Library/Developer/CoreSimulator/Devices/280905FB-023A-4FBD-A0DD-446C601862E5/data/Containers/Data/Application/5213D734-BB39-4788-B602-99CF74D00B12/Library/Caches/MyCache/httpwwwgysdjhyorgcnRollImageE1B259A50EFB4FACB1C0C1CFC3D14BDEpng.png}```
2.FileManager.default.fileExists(atPath: fullPath) 中的fullPath不需要前缀"file://"

读写操作错误解决: 全路径前面需要加```file://```前缀

//图片写入读取操作
func imageDataReadAndWrite() {

    let s:String = "http://www.gysdjhy.org.cn/RollImage/E1B259A50EFB4FACB1C0C1CFC3D14BDE.png"
    
    let image = UIImage.init(named: "test.jpg")
    let data = UIImageJPEGRepresentation(image!, 1.0)
    //写入缓存
    let fullPath = self.getFullCachePathFromUrl(url: s)
    let fullUrl = URL.init(string: fullPath)
    do {
        try data?.write(to: fullUrl!, options: Data.WritingOptions.atomic)
    }catch {
        print("写入缓存数据失败")
    }
    
    var resultData:Data? = Data.init()
    do {
        try resultData = Data.init(contentsOf: fullUrl!)
    }catch {
        print("读取缓存数据失败")
    }
    self.resultImgView.image = UIImage.init(data: resultData!)
}```
//设置缓存路径
    func getFullCachePathFromUrl(url:String)->String{
        
        let fileExtensionArr = url.components(separatedBy: ".")
        let fileExtension = fileExtensionArr.last
        
        var chchePath = NSHomeDirectory().appending(My_Image_Cache_Path)
        let fileManager:FileManager=FileManager.default
        fileManager.fileExists(atPath: chchePath)
        if !(fileManager.fileExists(atPath: chchePath)) {
            do {
                try fileManager.createDirectory(atPath: chchePath, withIntermediateDirectories: true, attributes: nil)
            }catch{
                NSLog("创建缓存路径失败")
            }
        }
        //进行字符串处理
        var newURL:String
        newURL = self.stringToWztString(str:url)
        chchePath = chchePath.appendingFormat("/%@.%@", newURL, fileExtension!)
        let result = "file://"+chchePath //"file://"+
        return result
    }
    //去除./
    func stringToWztString(str:String)->String{
        
        var newStr:String = String()
        for i in 0..=48&&c<=57)||(c>=65&&c<=90)||(c>=97&&c<=122){
                let temp_c = Character(UnicodeScalar(c)!)
                newStr.append(temp_c)
            }
        }
        return newStr.copy() as! String
    }```

你可能感兴趣的:(swift3.0 Data数据缓存write、read函数)