hi,
at some point, you need to read the items back into the program (you only write data in this program). and i think you want to write all of the Items in the array, not just a single Item. (i.e., your writeJSON function appends an item to the array, but then writes out only the one item appended (not the entire array).
this code should work for you: it declares the array of Items with a code block that will be executed the first time you code references the array variable. that code block will load what's out there on disk already.
struct Item: Codable {
var name: String
enum CodingKeys: String, CodingKey {
case name
}
}
var array: [Item] = {
do {
let fileURL = try FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("deneme.json")
let data = try Data(contentsOf: fileURL)
let decoder = JSONDecoder()
let items = try decoder.decode([Item].self, from: data)
return items
} catch {
print(error.localizedDescription)
return []
}
}()
i'd rewrite the writeJSON function to write out the whole array:
func writeJSON(items: [Item]) {
do {
let fileURL = try FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("deneme.json")
let encoder = JSONEncoder()
try encoder.encode(array).write(to: fileURL)
} catch {
print(error.localizedDescription)
}
}
from there, here's some basic code that shows you what's happening
// show what's out there already on disk
print(array.map({ $0.name }))
// append a few items and then write the array
array.append(Item(name: "hello"))
array.append(Item(name: "goodbye"))
array.append(Item(name: "C U L8R"))
writeJSON(items: array)
// append a few more items, and print the names
array.append(Item(name: "here is"))
array.append(Item(name: "more data"))
// show what's in the array
print(array.map({ $0.name }))
// save these last two as well.
writeJSON(items: array)
the first time you run this code (and there is no existing file on your desktop), your output will look like this:
The file “deneme.json” couldn’t be opened because there is no such file.
[]
["hello", "goodbye", "C U L8R", "here is", "more data"]
the second time you run, all the items from the first run will be there at the start, and you'll then add even more items, producing this output:
["hello", "goodbye", "C U L8R", "here is", "more data"]
["hello", "goodbye", "C U L8R", "here is", "more data", "hello", "goodbye", "C U L8R", "here is", "more data"]
hope that helps,
DMG