iosswiftios-app-extensionios-app-groupnskeyedunarchiver

Swift iOS Intent Extension: The data couldn't be read because it isn't in the correct format


I've been trying to add an iOS Siri Intent Extension to my app. There is a shared class between the main app and extension, and within that class it creates an array of objects and then uses UserDefaults to save/load them as needed. This works fine in the main app, but when the extension is run it throws the following error:

"The data couldn't be read because it isn't in the correct format."

I have App Groups enabled between the two, and all files shared as needed. Everything I've read on here and elsewhere says it should be as simple as this, but I can't figure out why the data would be in the wrong format when it's using the same class to load/save in both places. Using breakpoints, I can see that the data object is the same size between both apps, but if I view the contents it does appear different. I also tried storing the data to disk using containerURL(forSecurityApplicationGroupIdentifier: "group.xxxx") but ran into the same problems.

Any help is appreciated!

var arrayOfObjects = [MyObject]()

func save() {
    do {
        guard let defaults: UserDefaults = UserDefaults(suiteName: "group.xxxx") else {
            fatalError("Error loading user defaults")
        }

        let data = try NSKeyedArchiver.archivedData(withRootObject: arrayOfObjects, requiringSecureCoding: false)

        defaults.set(data, forKey: "objects")
        defaults.synchronize()
    } catch {
        print("Error: \(error.localizedDescription)")
    }
}

func load() {
    do {
        guard let defaults: UserDefaults = UserDefaults(suiteName: "group.xxxx") else {
            fatalError("Error loading user defaults")
        }

        if let data = defaults.data(forKey: "objects") {

            guard let objectData = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [MyObject] else {
                fatalError("Error reading data from archive")
            }
            arrayOfObjects = objectData
        }

    } catch {
        print("Error: \(error.localizedDescription)")
    }
}

Solution

  • I think you can not unarchiveTopLevelObjectWithData is because they are in the different app.

    you should use JSON format string to share data between your app and your extension.