ios - AlamofireImage 下载到 CoreData

标签 ios swift core-data alamofire

我想缓存图像和json中的少量数据以使其持久化我知道Alamofire Image有它自己的chade方法,但我猜只有当应用程序处于事件状态时,当应用程序关闭并再次打开时,chache被清除,所以我必须再次下载图像。所以 如果我的图片像这样下载

image.af_setImage(withURL: url)

可以保存

imageEntity.save(image.image)

不确定是否是确切的代码,但想法是将下载的图像保存到 CoreData 中的图像中。 以及此方法背后的任何想法,如果图像存在于 coreData 中,则 cjeck 并显示,如果不下载并保存到 coreData

最佳答案

CoreData 并不是为了存储 ImageData 或大数据(文件)而设计的,而只是存储字符串、日期、整数......就像普通数据库一样。

如果你想保存数据,你可以使用 AlamofireImageCache 并将图像标识符保存在 CoreData 实体中作为字符串。这是最简单的方法。

let imageCache = AutoPurgingImageCache(
    memoryCapacity: 100_000_000,
    preferredMemoryUsageAfterPurge: 60_000_000
)
imageCache.add(yourImage, withIdentifier: "YourImageIdentifier")
imageEntity.identifier = "YourImageIdentifier"

然后,如果你想获取图像,你可以这样做:

let cachedAvatar = imageCache.image(withIdentifier: imageEntity.identifier)

请查看 AlamofireImage 文档以获取有关缓存的更多信息:https://github.com/Alamofire/AlamofireImage

更新

如果您想在硬盘上创建自己的 ImageCache,这里有一个存储图像的示例:

func saveImage(image:UIImage){

     if let data = UIImagePNGRepresentation(image) {

            let documentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]!
            let filename = documentPath.appendingPathComponent("YourImageName")
            try? data.write(to: filename)
     }
}

func getImage(ForName name:String) -> UIImage?{ 
    let documentPath =    FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]!   
    let filename = documentPath.appendingPathComponent("YourImageName")         
     return UIImage(contentsOf:URL(fileURLWithPath: filename)) 
 }

希望有帮助! 皮埃尔

关于ios - AlamofireImage 下载到 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44974760/

相关文章:

iphone - 如何查看Core Data中已有的数据?

iPhone - 在 OSX 上创建核心数据结构并填充它们

ios - 如何将后退图标添加到左侧栏按钮?

iphone - 如何将 NSTimeInterval 转换为 int?

ios - 使用 xcodebuild 使用 macOS header

swift - 如何允许结构变量使用多个枚举?

swift - 我可以向 Stormpath 中的其他用户显示用户数据吗?

ios - Swift - 将数据从父 View Controller 传递到 subview Controller

ios - Swinject 中不同 ViewController 的依赖注入(inject)不一致,发布 Swift 3.0 更新 : why?

ios - NSArray 到 NSData 编码格式化