如何正确使用缓存? Swift 3.0

时间:2016-09-26 01:15:05

标签: ios swift caching

我使用缓存存储我在collectionView中下载的所有图像,当我仍然使用该应用程序时,它运行良好。当我按下主页按钮时,它会进入主屏幕,当我回到应用程序时,它会再次开始下载所有图像,我编写代码来检查cachedImg是否为零,它是否为零。这意味着当我离开应用程序时,应用程序仍在后台运行,缓存会自动删除。我想保留缓存,直到应用程序被杀死。如果有人有任何想法,请帮助我。非常感谢!!!

我用

func configureCell(gallery: Gallery, img: UIImage? = nil) {

    self.image = gallery
    if img != nil {
        self.OriginImage.image = img

    } else {

        DispatchQueue.main.async {
            let ref = DataService.instance.OriginImageStorageRef.storage.reference(forURL: self.image.imageUrl)
            ref.data(withMaxSize: 2 * 1024 * 1024, completion: { (data, err) in
                if err != nil {
                    print("Unable to download from Storage")
                } else {
                    if let imgData = data {
                        if let img = UIImage(data: imgData) {
                            ProfileVC.cache.setObject(img, forKey: self.image.imageUrl as NSString)
                            self.OriginImage.image = img

                        }
                    }
                }
            })
        }

    }



}

,然后我设置了对象

 if let img = ProfileVC.cache.object(forKey: image.imageUrl as NSString) {
            cell.configureCell(gallery: image, img: img)
            //CachedImg.append(img)
        } else {
            cell.configureCell(gallery: image)

        }

并在ViewCollection中调用它,

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Share",
        url: "Debate/{id}",
        defaults: new { controller = "Home", action = "Share", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

0 个答案:

没有答案