
When we need saved small amount of data then we use
UserDefaults but when we need large amount of data saved then what should we have to do?
Then we use File System.
File System to be letting users create as much data as they want, which means we want a better storage solution than just throwing thins into
UserDefaults and hoping for the best. iOS makes it very easy for
read and
write data from device storage and all apps get a directory for storing any kind of documents we want.
All iOS Apps ar sandboxed, which means they run in their own container with a hard to guess directory name. It's hared try to guess the directory where our app is installed, and instead need to rely on Apple's API for finding our app's documents directory.
FileManager: This class can provide us with the document directory for the current user. In theory this can return several path URLs, but we only ever care about the first one.
func getDocumentDirectory() -> URL {
//find all possible documents directories for this user
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
//just sent first one, which ought to be the only one
return paths[0]
}
We can reading data two way:
String(contentsOf: ) and
Data(contentsOf: )
and writing only one way:
write(to:)
Model:
First of all we need to created a Model for which type of data we wan to save in directory
struct Project: Codable {
let name: String
let department: String
let image: Data
}
We created a model name
Project where has three properties
name type of string,
department type of string and
image type of data.
This type of data we will save our directory and retrive data as needed.
Data Add In Array:
Now we should added some data in our array list which type of
Project
class ViewController: UIViewController {
var studentList: [Project] = [
Project(name: \"Joynal\", department: \"Science\", image: (UIImage(named: \"planeImage\")?.pngData())!),
Project(name: \"AR Rahman\", department: \"Multimedia\", image: (UIImage(named: \"planeImage\")?.pngData())!)
]
override func viewDidLoad() {
super.viewDidLoad()
}
}
Save Data In Directory:
func saveDataToFile(_ projects : [Project]){
let recData = try! JSONEncoder().encode(projects)
let path = getDocumentDirectory().appendingPathComponent(\"projectDirectoryFile\")
do{
try recData.write(to: path)
}catch{
print(\"Error Saving Projects : \(error)\")
}
}
Retrieve Data From Directory:
func getDataFromFile() -> [Project] {
let path = getDocumentDirectory().appendingPathComponent(\"projectDirectoryFile\")
let recData : Data!
do{
recData = try Data(contentsOf: path)
}catch{
print(\"Error while Fetching from File : \(error)\")
return []
}
let retreiveArray = try! JSONDecoder().decode([Project].self, from: recData!)
return retreiveArray
}
Final Project:
//
// ViewController.swift
// FileSystemDemo
//
// Created by Joynal Abedin on 11/6/22.
//
import UIKit
struct Project: Codable {
let name: String
let department: String
let image: Data
}
class ViewController: UIViewController {
var studentList: [Project] = [
Project(name: \"Joynal\", department: \"Science\", image: (UIImage(named: \"planeImage\")?.pngData())!),
Project(name: \"AR Rahman\", department: \"Multimedia\", image: (UIImage(named: \"planeImage\")?.pngData())!)
]
override func viewDidLoad() {
super.viewDidLoad()
//save Model
saveDataToFile(studentList)
let data = getDataFromFile() // get Prjoect Typle list of data
print(\"data List: \(data)\")
}
func getDataFromFile() -> [Project] {
let path = getDocumentDirectory().appendingPathComponent(\"projectDirectoryFile\")
let recData : Data!
do{
recData = try Data(contentsOf: path)
}catch{
print(\"Error while Fetching from File : \(error)\")
return []
}
let retreiveArray = try! JSONDecoder().decode([Project].self, from: recData!)
return retreiveArray
}
func saveDataToFile(_ projects : [Project]){
let recData = try! JSONEncoder().encode(projects)
let path = getDocumentDirectory().appendingPathComponent(\"projectDirectoryFile\")
do{
try recData.write(to: path)
}catch{
print(\"Error Saving Projects : \(error)\")
}
}
func saveInUserDefaults(){
UserDefaults.standard.set(UIImage(named: \"planeImage\")?.pngData(), forKey: \"data\")
let getData = UserDefaults.standard.data(forKey: \"data\")
let image = UIImageView(frame: CGRect(x: 10, y: 100, width: 100, height: 100))
self.view.addSubview(image)
image.image = UIImage(data: getData!)
}
func getDocumentDirectory() -> URL {
//find all possible documents directories for this user
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
//just sent first one, which ought to be the only one
return paths[0]
}
}
Project Repo:
https://github.com/Joynal279/FileSystemDemo
0 Comments
Leave a Comment