0

I create a data manager model, here it is:

public class DataManager {

// get documents directiory
static fileprivate func getDocumentDirectory() -> URL {
    if let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        return url
    } else {
        fatalError("Unable to access document directiory")
    }
}



// save any kind of codable objects
static func save <T: Encodable> (_ object: T, with filename: String) {
    let url = getDocumentDirectory().appendingPathComponent(filename, isDirectory: false)
    let encoder = JSONEncoder()

    do {
        let data = try encoder.encode(object)
        if FileManager.default.fileExists(atPath: url.path) {
            try FileManager.default.removeItem(at: url)
        }
        FileManager.default.createFile(atPath: url.path, contents: data, attributes: nil)
    } catch {
        fatalError(error.localizedDescription)
    }
}


// Load any kind of codable object
static func load <T: Decodable> (_ filename: String, with type: T.Type) -> T {
    let url = getDocumentDirectory().appendingPathComponent(filename, isDirectory:  false
    )
    if !FileManager.default.fileExists(atPath: url.path) {
        fatalError("File not found at path \(url.path)")
    }

    if let data = FileManager.default.contents(atPath: url.path) {
        do {
            let model = try JSONDecoder().decode(type, from: data)
            return model
        } catch {
            fatalError(error.localizedDescription)
        }
    } else {
        fatalError("Data is unavailable at path \(url.path)")
    }
}

// Load data from a file
static func loadData(_ filename: String) -> Data? {
    let url = getDocumentDirectory().appendingPathComponent(filename, isDirectory:  false
    )
    if !FileManager.default.fileExists(atPath: url.path) {
        fatalError("File not found at path \(url.path)")
    }

    if let data = FileManager.default.contents(atPath: url.path) {
        return data
    } else {
        fatalError("Data is unavailable at path \(url.path)")
    }
}


//Load all files from a directory
static func loadAll <T:Decodable> (_ type: T.Type) ->[T] {
    do {
        let files = try FileManager.default.contentsOfDirectory(atPath: getDocumentDirectory().path)
        var modelObjects = [T]()

        for filename in files {
            modelObjects.append(load(filename, with: type))
        }

        return modelObjects

    } catch {
        fatalError("Could not load any files")
    }
}



//Delete file
static func delete (_ filename: String) {
    let url = getDocumentDirectory().appendingPathComponent(filename, isDirectory: false)

    if FileManager.default.fileExists(atPath: url.path) {
        do {
            try FileManager.default.removeItem(at: url)
        } catch {
            fatalError(error.localizedDescription)
        }
    }
}

}

I added all the code that somehow you need to answer me.

From this data manager, I created an array in the controller to show the data

 var activity = DataManager.loadAll(Activity.self)

And when I save data from this method, it's going to save perfectly, but this array is not updated instantly to get data from it, I have to close the app, and when I open it again, this array is updated with the latest data. What is your suggestion about it? Many thanks

Also in my model, I have a function for saving data

 func saveItem() {
    DataManager.save(self, with: identifier.uuidString)
}

and In the controller, I save data like that

 let newActivity = Activity(title: "Test todo", isDone: false, DeteOfCreation: Date(), identifier: UUID())

 newActivity.saveItem()
David
  • 27
  • 4
  • I see your code on how you are saving objects - but what happens when you are trying to reference them? Do you get `"Could not load any files"`? – impression7vx Aug 27 '19 at 23:45
  • No the data is saved perfectly,. But the array that contain data is not updated until I have to close app and open it again, Then, this array will be updated. First I thought It was the problem of the tableview, but I print the number of item in the array, I saw it's not updated until the app is opened again – David Aug 27 '19 at 23:53
  • Yea, so when you save the data -- are you filling the array afterwards...? Just cause you save something to `docDir` doesn't mean any data gets filled locally to current methods/variables. – impression7vx Aug 27 '19 at 23:54
  • I edited the first post that how I can save data, please check it, I really appreciate for your time. – David Aug 28 '19 at 00:07
  • Sure, but where are you calling your array to be updated? Saving your code looks fine and always has - but where do you update your array? – impression7vx Aug 28 '19 at 00:17
  • This array shows data in the local storage, should it be updated automatically? becuase when I open the app again, it is updated. – David Aug 28 '19 at 00:20
  • Tbh - i don't even know the array you are talking about. I don't see it above. – impression7vx Aug 28 '19 at 00:23
  • this array: `var activity = DataManager.loadAll(Activity.self)` – David Aug 28 '19 at 00:25
  • Check that your path is the same -- when you save `url` and your loadAll `url` and see if they equate – impression7vx Aug 28 '19 at 00:39
  • Thank you so much for your help. I found out where is my problem – David Aug 28 '19 at 01:01

0 Answers0