【问题标题】:How to cache images in IOS App with expiry age using swift如何使用 swift 在 IOS 应用程序中使用过期时间缓存图像
【发布时间】:2016-01-09 11:51:48
【问题描述】:

在 iOS 应用程序中,如何缓存具有指定有效期的图像?有关于如何存储和检索图像的示例,但是如何设置过期时间以自动删除旧图像?

【问题讨论】:

    标签: ios swift image-caching


    【解决方案1】:

    正如 Fahri 所指出的,您需要自己管理缓存(或使用开源库)。您可以轻松地创建一个缓存目录来存储您的图像。然后,在应用程序启动时,您解析此图像缓存目录以检查图像创建日期、检查时间并删除超过指定年龄的图像。

    下面的 Swift 代码将完成这个解析/删除工作,我将指定的年龄设置为 30,000(秒)

    // We list the stored images in Caches/Images and delete old ones
    let cacheDirectory =  NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL
    let filelist = try? filemanager.contentsOfDirectoryAtPath(cacheDirectory.path!)
    var newDir = cacheDirectory.URLByAppendingPathComponent("Images")
    var properties = [NSURLLocalizedNameKey, NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey]
    var URLlist = try? filemanager.contentsOfDirectoryAtURL(newDir, includingPropertiesForKeys: properties, options: [])
    if URLlist != nil {
        for URLname in URLlist! {
            let filePath = URLname.path!
            let attrFile: NSDictionary? = try? filemanager.attributesOfItemAtPath(filePath)
            let createdAt = attrFile![NSFileCreationDate] as! NSDate
            let createdSince = fabs( createdAt.timeIntervalSinceNow )
            #if DEBUG
                 print( "file created at \(createdAt), \(createdSince) seconds ago" )
            #endif
            if createdSince > 30000 {
                let resultDelete: Bool
                do {
                     try filemanager.removeItemAtPath(filePath)
                     resultDelete = true
                } catch _ {
                     resultDelete = false
                }
                #if DEBUG
                    print("purging file =\(filePath), result= \(resultDelete)")
                #endif
            }
        }
    }
    

    【讨论】:

    • 谢谢@Daniel Mavrakis。它有效并解决了我的问题
    【解决方案2】:

    Web 就是 Web,iOS 就是 iOS。如果你想创建有过期的图片缓存,你必须自己实现,或者使用开源的lib。我可以给你一个想法,实施起来并不难。因此,除了存储和检索功能之外,您还需要添加元数据管理方法,使用这些方法您可以知道添加图像的时间,该图像的到期日期是什么,以及何时发生某些事件(应用程序变得活跃,运行到背景等),您应该检查图像的元数据,如果过期日期已过,请删除图像。就是这样,没什么难的。祝你好运!

    P.S.:在一些 git 源项目中,我看到了您正在寻找的功能,请查看 github 上的DFCache,也许它适合您的需求。

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      相关资源
      最近更新 更多