Store and Retrieve Image Locally Swift - Image Cache without Libraries - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

26 Oct 2017

Store and Retrieve Image Locally Swift - Image Cache without Libraries

Store images locally without using any other libraries. In this article we will store and retrieve images using our own code.

We are storing images in a Document Directory. It's different for each app, so we can store image inside Document Directory.

Save and Get Image from Document Directory in Swift ?Best practice to save Images locally ios,swift image cache library,How To Save An Image Locally In Xcode,Persisting Image Data Locally swift 4

Create sample Xcode project.

Storing Images:

First create new swift file and import UIKit as follow:

import UIKit

class SSCache: NSObject {

/..........

}

Add the following method for getting the current document directory:

private func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

Next create method for saving image locally, add following method:

func saveImage(image: UIImage, Key: String) {
    if let data = UIImagePNGRepresentation(image) {
        let filename = getDocumentsDirectory().appendingPathComponent("\(Key).png")
        print(filename)
        try? data.write(to: filename)
    }
}

In above method we are passing image and key for storing image.

Next add the following Singleton object:

static let sharedInstance = SSCache()

Usage:

We can use as follow for storing image.

Open ViewController.swift file and add the following code:

let image = UIImage(named: "bg.jpg")
SSCache.sharedInstance.saveImage(image: image!, Key: "backgroundImage")

Build and Run, now image stored locally.

So we can easily use in any class as above.

Get Image:

For getting image from document directory, add the following method inside SSCache class:

func getImage(Key: String) -> UIImage?{
    let fileManager = FileManager.default
    let filename = getDocumentsDirectory().appendingPathComponent("\(Key).png")
    if fileManager.fileExists(atPath: filename.path) {
        return UIImage(contentsOfFile: filename.path)
    }
    return nil
}

Here we need the image name for retrieving.

Usage:

Simple we can add the following line for getting image:

if let image = SSCache.sharedInstance.getImage(Key: "backgroundImage") {
    print("we got image \(image)")
}

Build and Run, we will get above message.

Download sample project with examples :

1 comment:

  1. this blog was really great, never seen a great blog like this before. i think im gonna share this to my friends.. Media Files Optimizer

    ReplyDelete

Post Top Ad