美文网首页
swift - 图片存储

swift - 图片存储

作者: GA_ | 来源:发表于2017-03-14 15:23 被阅读98次
    //
    //  GA_CachesImage.swift
    //  GA_BrowseImage
    //
    //  Created by houjianan on 2016/12/5.
    //  Copyright © 2016年 houjianan. All rights reserved.
    //
    
    import UIKit
    
    private let c: GA_CachesImage = GA_CachesImage()
    class GA_CachesImage: NSObject {
        
        class var share: GA_CachesImage {
            return c
        }
        
        func writeLocalImage(data: Data, key: String) {
            DispatchQueue.global().async {
                let path = self.createPath()
                self.removeItem(atPath: path, key: key)
                if FileManager.default.isWritableFile(atPath: path) {
                    try! data.write(to: URL(fileURLWithPath: path + key))
                }
            }
        }
        
        func writeLocal(image: UIImage, key: String) {
            DispatchQueue.global().async {
                print(key)
                let path = self.createPath()
                self.removeItem(atPath: path, key: key)
                if FileManager.default.isWritableFile(atPath: path) {
                    try! UIImageJPEGRepresentation(image, 1)?.write(to: URL(fileURLWithPath: path + key))
                }
            }
        }
        
        func readLocalData(key: String) -> Data? {
            if FileManager.default.fileExists(atPath: createPath() + key) {
                return try! Data(contentsOf: URL(fileURLWithPath: createPath() + key))
            }
            return nil
        }
        
        func readLocalImage(key: String) -> UIImage? {
            if let imageData = readLocalData(key: key) {
                return UIImage(data: imageData)
            }
            return nil
        }
        
        func deleteLocal(key: String) {
            removeItem(atPath: createPath(), key: key)
        }
        
        private func createPath() -> String {
            let newPath = NSHomeDirectory() + "/Documents/images/"
            
            if !FileManager.default.fileExists(atPath: newPath) {
                print(newPath)
                try! FileManager.default.createDirectory(atPath: newPath, withIntermediateDirectories: true, attributes: nil)
            }
            return newPath
        }
        
        private func removeItem(atPath: String, key: String) {
            if FileManager.default.fileExists(atPath: atPath + key) {
                try! FileManager.default.removeItem(atPath: atPath + key)
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:swift - 图片存储

          本文链接:https://www.haomeiwen.com/subject/ilkhnttx.html