ios 17 widget 无法正确更新 core data

12 天前
 izzy27

我正在开发的一个 iOS 17 Widget ,它可以为用户的 Thing 对象进行打卡。

当我同时创建多个 Widget 实例时,无论点击哪个 Widget 实例进行打卡,它们更新的都是第一个 Thing ,看起来多个 Widget 都重复指向了同一个 Thing 。

我后面经过排查,发现是我的 AppIntent 中,Parameter 并不起作用,用户无论选择哪个 thing,perform 中的 thing 都是 EntityQuery 中的 defaultResult 的返回值

struct ConfigurationAppIntent: WidgetConfigurationIntent {
    @Parameter(title:"Select thing")
    var thing: ThingData
    
    func perform() async throws -> some IntentResult {
            print("perform thing: \(thing)") // 这里会直接返回 defaultResult 的结果,而不是用户选择的 thing
	}
}

    // EntityQuery 中的代码
    // AppIntent 中的 thing ,永远是这里的返回结果,而不是用户选择的结果
    func defaultResult() async -> ThingData? {
        logger.info("Entering defaultResult()")
        
        let context = PersistenceController.shared.viewContext
        let fetchRequest: NSFetchRequest<Thing> = Thing.fetchRequest()
        fetchRequest.fetchLimit = 1

        do {
            let things = try context.fetch(fetchRequest)
            things.forEach { logger.info("Default Thing: \($0.description)") }
            logger.info("Exiting defaultResult()")
            return things.first?.toThingData()
        } catch {
            logger.error("Error fetching default result: \(error.localizedDescription)")
            logger.info("Exiting defaultResult()")
            return nil
        }
    }

而且这样会有一个问题,比如说我有五六个 thing ,用户为每个 thing 都添加了一个 widget ,但是由于这个 bug 的存在,导致只有 defaultResult 返回的 Thing 会更新,其他都不会更新

哪位大佬知道怎么解决吗?修了两天了,文档、视频、教程看了一遍,都没发现解决办法。。真的很痛苦 T_T

196 次点击
所在节点    Swift
1 条回复
izzy27
12 天前
解决了各位,调用的时候得加上初始化参数,不然会使用默认的 defaultResult
```
if let thing = entry.thingData{
Button(intent: ConfigurationAppIntent(thing: thing)){
Image(systemName: "checkmark")
}
}
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1050259

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX