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.
Create sample Xcode project.
Add the following method for getting the current document directory:
Next create method for saving image locally, add following method:
In above method we are passing image and key for storing image.
Next add the following Singleton object:
Open ViewController.swift file and add the following code:
Build and Run, now image stored locally.
So we can easily use in any class as above.
Here we need the image name for retrieving.
Build and Run, we will get above message.
Download sample project with examples :
We are storing images in a Document Directory. It's different for each app, so we can store image inside Document Directory.
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 :
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