/Class_Students_AddApp_SwiftUI

Class Students Add - SwiftUI Application

Primary LanguageSwift

Class Students Add App

Made it in Swift and SwiftUI, this is a training applications where I learned the basic concepts about Data Persistence in iOS development using Plist.

º Data Persistence with Plist
º MVVM

Untitled

About the Plist storage


  1. I created a class to create a Plist file
class StorageHandler {
    static private var plistURL: URL {
        let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        return documents.appendingPathComponent("students.plist")
    }
}

In this class there's this computed property ULR type, with this procolo it can be changed in execution time

static private var plistURL: URL {}

This is used to locate the documents directory inside the app's sandbox. Everything added to this sandbox can be modified by iOS at any time.

let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

Here I'm adding a Plist file in the documents directory

return documents.appendingPathComponent("students.plist")

  1. Now I'm writing into the Plist file
static func write(item: Student) {
    if !FileManager.default.fileExists(atPath: plistURL.path) {
        FileManager.default.createFile(atPath: plistURL.path, contents: prepareData([item]), attributes: nil)
        
        print(plistURL.path)
    } else {
        var currentItens = StorageHandler.load()
        currentItens.append(item)
        try? prepareData(currentItens).write(to: plistURL)
    }
}

  1. To consulting
static func load() -> [Student] {
    let decoder = PropertyListDecoder()
    
    guard let data = try? Data.init(contentsOf: plistURL), let preferences = try? decoder.decode([Student].self, from: data)
        else { return [] }
            
    return preferences
}

  1. To delete the Plist file from documents directory
static func deleteAll() {
        
    if FileManager.default.fileExists(atPath: plistURL.path) {
        
        try? FileManager.default.removeItem(at: plistURL)
        
    }
}

  1. This method packages data to easely be required and used in a simple way
static func prepareData(_ value: [Student]) -> Data {
        
        let encoder = PropertyListEncoder()
        
        guard let data = try? encoder.encode(value) else {
            return Data()
        }
        
        return data
    }
}