我正在尝试为我的iOS 15小部件实现动态提供的选项。到目前为止,我成功地实现了静态意图参数,现在我想用动态提供的参数来扩展它。我的.intentdefinition文件中的动态参数称为HotspotList
,并具有String
类型。
我已经定义了一个结构,在这里我还保存了一个availableHotspots
列表
struct Hotspot: Hashable, Identifiable, Codable {
...
static var availableHotspots = UserDefaults.standard.object(forKey: "hotspots") as? [String] ?? []
}
我已经检查了这个数组是否在主视图中的某个地方用print(Hotspot.availableHotspots)
成功保存。
现在,我想在我的IntentHandler.swift文件中使用这个数组:
import Intents
class IntentHandler: INExtension, WidgetConfigurationIntentHandling {
override func handler(for intent: INIntent) -> Any {
return self
}
func provideHotspotListOptionsCollection(for intent: WidgetConfigurationIntent) async throws -> INObjectCollection<NSString> {
let hotspots: [NSString] = Hotspot.availableHotspots.map { element in
let nsstring = element as NSString
return nsstring
}
let collection = INObjectCollection(items: hotspots)
return collection
}
func defaultHotspotList(for intent: WidgetConfigurationIntent) -> String? {
return "thisIsJustATest"
}
}
我看到意图的实现是正确的,因为defaultHotspotList()返回默认参数。但是provideHotspotListOptionsCollection()不返回String的列表。我做错了什么?
注意:我还尝试了函数的非异步选项:
func provideHotspotListOptionsCollection(for intent: WidgetConfigurationIntent, with completion: @escaping (INObjectCollection<NSString>?, Error?) -> Void) {
let hotspots: [NSString] = Hotspot.availableHotspots.map { element in
let nsstring = element as NSString
return nsstring
}
let collection = INObjectCollection(items: hotspots)
print(collection)
completion(collection, nil)
}
发布于 2022-04-02 11:16:56
因此,有了@loremipsum的暗示,我就能自己解决了。对于任何感兴趣的人,以下是我的解决方案:
我在应用程序目标中的MainView中添加了以下行:
struct MainView: View {
@AppStorage("hotspots", store: UserDefaults(suiteName: "group.com.<<bundleID>>"))
var hotspotData: Data = Data()
...
save(hotspots: miners)
...
func save(hotspots: [String]) {
do {
hotspotData = try NSKeyedArchiver.archivedData(withRootObject: hotspots, requiringSecureCoding: false)
WidgetCenter.shared.reloadAllTimelines()
} catch let error {
print("error hotspots key data not saved \(error.localizedDescription)")
}
}
然后检索IntentHandler.swift中的数据:
import Intents
import SwiftUI
class IntentHandler: INExtension, WidgetConfigurationIntentHandling {
@AppStorage("hotspots", store: UserDefaults(suiteName: "group.com.<<bundleID>>"))
var hotspotData: Data = Data()
func provideHotspotListOptionsCollection(for intent: WidgetConfigurationIntent) async throws -> INObjectCollection<NSString> {
var hotspots: [String] {
var hotspots: [String]?
do {
hotspots = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(hotspotData) as? [String]
} catch let error {
print("color error \(error.localizedDescription)")
}
return hotspots ?? []
}
let NSHotspots: [NSString] = hotspots.map { element in
let nsstring = element as NSString
return nsstring
}
let collection = INObjectCollection(items: NSHotspots)
return collection
}
https://stackoverflow.com/questions/71707500
复制相似问题