MarksCode
MarksCode

Reputation: 8584

Caching images in Swift?

I'm downloading images and displaying them each time the user visits a particular view. To make it more efficient I want to start caching so instead of fetching from the database the user already has the images downloaded.

From my research I found a bunch of Swift libraries that handle caching for you, such as HanekeSwift, KingFisher, and Nuke. I'm wondering what the difference is between using one of these libraries and just downloading the image to Core Data.

As far as I know, the first time a user downloads the images I can just save them to Core Data and check if they exist by key the next time. Are there any advantages to using one of these libraries instead?

Upvotes: 1

Views: 2943

Answers (1)

Jose Castellanos
Jose Castellanos

Reputation: 548

You shouldn't save images to core data. You should save them to files and then if you want you can store the path or file name or other attributes about the image in core data. You can save the images to your apps documents directory for instance with the following code.

let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String

if let filePath = dir.stringByAddingPathComponent("filename.png"){
  try? UIImagePNGRepresentation(image)?.write(to: URL(fileURLWithPath: filePath))
}

If you want to save to a sub folder just use FileManager to make sure the sub folder has been created and create it if not.

Upvotes: 3

Related Questions