1

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!

flowy12
  • 11
  • 3
  • 3
    why are you appending this part? `groupUrl.appendingPathComponent("group.com.myName.appName")`, Are you trying to create subfolders? Just return groupUrl without appending anything – RJE Oct 27 '19 at 16:22
  • Are you sure the directory you're trying to access actually exists? Some directories (even those listed in official docs) need to be created first – Bartosz Kunat Oct 27 '19 at 17:04
  • 1
    Just like RJE says, try it without appending to the path. The periods in it are likely messing it up as a path. Just use `return groupUrl`. – Chris Oct 27 '19 at 18:38
  • @RJE @Chris @Bartosz Kunat Thank you so much guys, `appendingPathComponent` was the mistake. Such an obvious one too. I'll be sure to question every line of code next time. – flowy12 Oct 28 '19 at 05:51

0 Answers0