Giridhar
Giridhar

Reputation: 512

How to cache images in IOS App with expiry age using swift

In an iOS app, how can I cache an image with specified expiry age? There are examples on how to store and retrieve images, but how can I set an expiry period to auto delete old images?

Upvotes: 3

Views: 2393

Answers (2)

Daniel Mavrakis
Daniel Mavrakis

Reputation: 592

As indicated by Fahri, you will need to manage the cache yourself (or using an open source library). You could easily create a cache directory to store your images. Then, at application launch, you parse this image cache directory to check image creation date, check time elapsed and remove those older than the specified age.

The below Swift code will do this parsing/removing job, I set the specified age to 30,000 (seconds)

// 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
        }
    }
}

Upvotes: 3

Fahri Azimov
Fahri Azimov

Reputation: 11768

Web is web, iOS is iOS. If you want to create image cache with expiration, you have to implement it yourself, or use open source lib. I can give you the idea, it's not hard to implement. So, in addition to storing and retrieving functionality, you also need to add metadata management methods, using which you could know when the image was added, and what's the expiration date for that image, and when some events occur (app become active, going to background etc.) you should check the meta for your images, and delete the image if the expiration date passed. That's it, nothing hard. Good luck!

P.S.: In some git source projects I have seen the functionality your are looking for, check DFCache on github, maybe it suits your needs.

Upvotes: 0

Related Questions