Beginner(?) question here. I searched StackOverflow and tried several solutions but was unable to solve this issue - I'm can't save anything to the App Group directory created after adding the App Groups capability to the target.
The saving works fine when I try to write to the Document directory though. And earlier, before switching to simple JSON persistence, write and read to App Groups was working fine when I was using Core Data.
Attached is my code in the DataManager singleton class:
func getAppGroupURL() -> URL {
if let groupUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.myName.appName") {
print("Group Directory exists.")
return groupUrl.appendingPathComponent("group.com.myName.appName")
} else {
print("Couldn't find directory, reverting to default.")
let appUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
return appUrl
}
}
func saveToJSON(entries: [Entry]) {
let groupURL = DataManager.shared.getAppGroupURL()
let jsonURL = groupURL.appendingPathComponent("entries").appendingPathExtension("json")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let jsonData = try encoder.encode(entries)
try jsonData.write(to: jsonURL)
print("Encoded JSON data is:")
print(String(data: jsonData, encoding: .ascii)!)
} catch {
print("Error encoding: " + error.localizedDescription)
}
}
func getFromJSON() -> [Entry]? {
let groupURL = DataManager.shared.getAppGroupURL()
let jsonURL = groupURL.appendingPathComponent("entries").appendingPathExtension("json")
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .secondsSince1970
do {
let data = try Data(contentsOf: jsonURL)
print("JSON data is: " + String(data: data, encoding: .ascii)!)
let entries = try decoder.decode([Entry].self, from: data)
print("Decoded JSON data is: \(entries)")
return thingItems
} catch {
print("Error decoding: " + error.localizedDescription)
return nil
}
}
I get this error message when I try to use the saveToJSON function, or even the FileManager's createFile(atPath:) function to write:
Group Directory exists. Error encoding: The file “entries.json” doesn’t exist.
And when trying to use the getFromJSON function to save, I get: Error decoding: The file “entries.json” couldn’t be opened because there is no such file.
Again, it all works when I use the default documents directory, I'm able to persist and read, but not with the app group directory...I'd really appreciate if someone could point out what's wrong here!