如何从Kingfisher中将图像作为NSData写入Realm?

时间:2016-10-22 13:55:57

标签: ios swift xcode realm kingfisher

我使用swift 2.3Realm databaseKingfisher framework进行应用以获取图片。 我通过JSON

从服务器获取图片
let urls = NSURL(fileURLWithPath: newsRealm.newsImage)
let prefetcher = ImagePrefetcher(urls: [urls], optionsInfo: nil, progressBlock: nil, completionHandler: {
(skippedResources, failedResources, completedResources) -> () in
print("These resources are prefetched: \(completedResources)")
})
prefetcher.start()

它已成功,但Realm database中的图片为NSData,如何将收到的数据从Kingfisher写入Realm NSData

领域类:

class News: Object {
  dynamic var newsImage: String = ""
  dynamic var images: NSData?
}

嗨!我无法将我的图像写入我的数据库:

let urls = NSURL(fileURLWithPath: newsRealm.newsImage)
let prefetcher = ImagePrefetcher(urls: [urls], optionsInfo: nil, progressBlock: nil, completionHandler:
{(skippedResources, failedResources, completedResources) -> () in
print("These resources are prefetched: (completedResources.description)")
let images: [NSData] = completedResources
newsRealm.images = images

2 个答案:

答案 0 :(得分:1)

使用optionsInfo: [.TargetCache(myCache)]设置缓存网址,您可以在其中检索数据(如here所述), 或使用example retrieveImage  检索UIImage,可以转换为NSData,如here

答案 1 :(得分:0)

completedResources不是NSData的数组。 completedResourcesResource的数组。 Resource拥有cacheKeydownloadURL。您应该使用cacheKey从缓存中检索图像,然后将图像转换为NSData。然后将数据存储到Realm。

let images: [NSData] = completedResources.map { (resource) -> NSData in
    let image = ImageCache.default.retrieveImageInDiskCache(forKey: resource.cacheKey)!
    return UIImagePNGRepresentation(image)
}