Widget参数默认值失效:BackgroundQuery defaultResult不生效排查
Widget配置参数默认值不一致问题排查
我开发的Widget支持location和background两个自定义参数,location选择器能正常遵循LocationQuery的defaultResult设置默认值,但background选择器却忽略BackgroundQuery的defaultResult,Xcode抛出如下警告:
Error getting AppIntent from LNAction: AppIntent has missing parameter value for 'background'. You may need to set a default value in the initializer of your @Parameter, or using the default method on your Query.
No AppIntent in timeline(for:with:)
请问为何两者表现不一致?
相关代码
struct BackgroundQuery: EntityQuery { func entities(for identifiers: [String]) -> [WidgetBackground] { [ WidgetBackground(id: "Background1"), WidgetBackground(id: "Background2") ].filter { identifiers.contains($0.id) } } func suggestedEntities() -> [WidgetBackground] { [ WidgetBackground(id: "Background1"), WidgetBackground(id: "Background2") ] } func defaultResult() -> WidgetBackground { return WidgetBackground(id: "Background1") } } struct WidgetBackground: AppEntity { var id: String static var typeDisplayRepresentation: TypeDisplayRepresentation = "Background" static var defaultQuery = BackgroundQuery() var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(NSLocalizedString(id, comment: "").description)") } init(id: String) { self.id = id } } struct LocationQuery: EntityQuery { func entities(for identifiers: [LocationDetail.ID]) async throws -> [LocationDetail] { LocationDetail.getAllLocations().filter { identifiers.contains($0.id) } } func suggestedEntities() async throws -> [LocationDetail] { LocationDetail.getAllLocations() } func defaultResult() async -> LocationDetail? { try? await suggestedEntities().first } } struct SelectLocationIntent: WidgetConfigurationIntent { static var title: LocalizedStringResource = "Avalanche Reports Location" static var description = IntentDescription("Select the location of the displayed avalanche reports.") @Parameter(title: "Location") var locationDetail: LocationDetail @Parameter(title: "Background") var background: WidgetBackground }
问题原因与解决方案
核心问题是两个EntityQuery的defaultResult方法签名不匹配:
LocationQuery使用了Widget配置Intent要求的现代异步可选签名:async -> LocationDetail?BackgroundQuery仍用旧的同步非可选签名:-> WidgetBackground
系统无法识别同步版本的defaultResult,因此认为background参数缺少默认值,抛出警告。
修改BackgroundQuery的方法签名,对齐异步可选模式,同时将其他查询方法也改为异步:
struct BackgroundQuery: EntityQuery { func entities(for identifiers: [String]) async -> [WidgetBackground] { [ WidgetBackground(id: "Background1"), WidgetBackground(id: "Background2") ].filter { identifiers.contains($0.id) } } func suggestedEntities() async -> [WidgetBackground] { [ WidgetBackground(id: "Background1"), WidgetBackground(id: "Background2") ] } func defaultResult() async -> WidgetBackground? { WidgetBackground(id: "Background1") } }
这样修改后,background参数的默认值就能被系统正确加载,和location参数的表现一致。
内容的提问来源于stack exchange,提问作者Fez Vrasta
相关产品推荐
相关产品推荐

