SwiftData `context.fetch()` possible bug on WidgetKit EntityQuery

I'm developing an app with dynamic intents fetched from a SwiftData container with data that is configured inside the app. However, the following happens when .fetch() is run during widget configuration.

  • When creating a new instance of the model and inserting it into the container, it disappears when the app is relaunched.
  • When creating a new instance of the model and inserting it into the container, and then attempting to delete that instance, the app crashes. This error shows up Could not cast value of type 'Swift.Optional<Any>' (0x2003ddfc0) to 'Foundation.UUID' (0x200442af8).

This is a snippet of the query code.

func entities(for identifiers: [ExampleEntity.ID]) async throws -> [ExampleEntity] {
        let modelContext = ModelContext(Self.container)
        let examples = try? modelContext.fetch(FetchDescriptor<ExampleModel>())
        
        return examples?.map {
            ExampleEntity(example: $0)
        } ?? []
}

SwiftData works as expected as long as the .fetch() is not called in the EntityQuery.

Answered by frncg in 774565022

I managed to fix the issue. I think it had something to do with the targets of the intent swift file. I did some restructuring and it worked flawlessly.

Models created after .fetch() is run also does not appear when it is called again in the widget configuration screen. It only shows models created before the first .fetch() was called and any changes made to those models such as edits or deletion.

Accepted Answer

I managed to fix the issue. I think it had something to do with the targets of the intent swift file. I did some restructuring and it worked flawlessly.

Hi All,, I have some requirement where I don't want to show the widget to some of the users. And have a control in my app to enable the widget later. Is it possible? if yes, is it acceptable by apple? Any help would be appreciated.

SwiftData `context.fetch()` possible bug on WidgetKit EntityQuery
 
 
Q