How can I create a AppIntent with SwiftData correctly?

I currently create a AppIntent that contains a custom AppEntity, it shows like this

struct GetTimerIntent: AppIntent {
    static let title: LocalizedStringResource = "Get Timer"
    
    @Parameter(title: "Timer")
    var timer: TimerEntity
    
    func perform() async throws -> some IntentResult {
        .result(value: timerText(timer.entity))
    }
    
    static var parameterSummary: some ParameterSummary {
        Summary("Get time of \(\.$timer)")
    }
    
    func timerText(_ timer: ETimer) -> String {
        // Implementation Folded
    }
}

struct TimerEntity: AppEntity {
    var entity: ETimer
    
    static let defaultQuery: TimerQuery = .init()
    
    static var typeDisplayRepresentation: TypeDisplayRepresentation {
        TypeDisplayRepresentation(name: "Timer")
    }
    
    var id: UUID {
        entity.identifier
    }
    
    var displayRepresentation: DisplayRepresentation {
        DisplayRepresentation(title: "\(entity.title)")
    }
}

To get the timers, I create a TimerQuery type to fetch them from SwiftData containers.

struct TimerQuery: EntityQuery, Sendable {
    func entities(for identifiers: [UUID]) async throws -> [TimerEntity] {
        print(identifiers)
        let context = ModelContext(ModelMigration.sharedContainer)
        
        let descriptor = FetchDescriptor<ETimer>(
            predicate: #Predicate {
                identifiers.contains($0.identifier)
            },
            sortBy: [.init(\.index)]
        )
        let timers = try context.fetch(descriptor)
        print(timers.map(\.title))
        
        return timers.map {
            TimerEntity(entity: $0)
        }
    }
}

Everything looks make sense since I code it. When I'm testing, the console jump No ConnectionContext found for 105553169752832 and I can't get my datas.

How can I solve this issue?

I am by no means an AppIntent specialist, and will see if AppIntent folks can provide more meaningful comment, but does your debugging process point to something wrong in SwiftData? If yes, I'll be very interested in taking a look...

Regarding the question in your post title, the SwiftData version of the following sample code demonstrates how to use SwiftData in an AppIntent:

The sample doesn't demonstrate AppEntity, but contains an AppIntent that makes the widget actionable, which I think is relevant.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

How can I create a AppIntent with SwiftData correctly?
 
 
Q