swift - 图片存储

2017-03-14  本文已影响98人  GA_
//
//  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)
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读