Swift下载图片(缓存图片)储存到沙盒中

下载图片一定有下载和读取,下面上代码先来下载:

    func downLoadImage(str:String){
        if let url = NSURL(string: str) {
            if let data = NSData(contentsOfURL: url){
                let img = UIImage(data: data)
                let home = NSHomeDirectory() as NSString
//打印沙盒路径,可以前往文件夹看到你下载好的图片
                print(home)
                let docPath = home.stringByAppendingPathComponent("Documents") as NSString                
                let filePath = docPath.stringByAppendingPathComponent("666.png")
//不得补多少一句在这里卡主了,搜了很多地方都不知道这里怎么写,后来查文档看着需要抛出(try)
                do {
                     try UIImagePNGRepresentation(img!)?.writeToFile(filePath, options: NSDataWritingOptions.DataWritingAtomic)
                }catch _{
                    
                }
          }
        
       }
    }

读取下载好的图片:无非就是获得路径,读取图片

    func readWithFile() {
        let home = NSHomeDirectory() as NSString;
        let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
        /// 获取文本文件路径
        let filePath = docPath.stringByAppendingPathComponent("666.png");
        let image = UIImage.init(contentsOfFile: filePath)
        if image == nil {
            imageView.image = UIImage(named: "333.jpg")
        }else{
            imageView.image = image
        }
        
        print(filePath)
    }

你可能感兴趣的:(Swift下载图片(缓存图片)储存到沙盒中)