Reputation: 1036
I'm currently developing an application using SwiftUI.
I want to reload data from CoreData in IntentHandler
to update newer data every when I close a host App.
In the case of Widget
, we can use WidgetCenter.shared.reloadAllTimelines()
to update, but how can we update data in the case of IntentHandler
?
In my codes, data in a list of editing view in the widget receive data only when the host app boots for the first time.
Here are the codes:
TimerApp.swift (Host APP)
import SwiftUI
import WidgetKit
@main
struct TimerApp: App {
@Environment(\.scenePhase) private var scenePhase
let persistenceController = PersistenceController.shared.managedObjectContext
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController)
.onChange(of: scenePhase) { newScenePhase in
if newScenePhase == .inactive {
// I want to update a data in IntentHandler here
}
}
}
}
}
IntentHandler.swift (IntentsExtension)
import WidgetKit
import SwiftUI
import CoreData
import Intents
class IntentHandler: INExtension, ConfigurationIntentHandling {
var moc = PersistenceController.shared.managedObjectContext
var timerEntity:TimerEntity?
func provideNameOptionsCollection(for intent: ConfigurationIntent, searchTerm: String?, with completion: @escaping (INObjectCollection<NSString>?, Error?) -> Void) {
let request = NSFetchRequest<TimerEntity>(entityName: "TimerEntity")
do{
let result = try moc.fetch(request)
timerEntity = result.first
}
catch let error as NSError{
print("Could not fetch.\(error.userInfo)")
}
let nameIdentifiers:[NSString] = [
NSString(string: timerEntity?.task ?? ""),
]
let allNameIdentifiers = INObjectCollection(items: nameIdentifiers)
completion(allNameIdentifiers,nil)
}
override func handler(for intent: INIntent) -> Any {
return self
}
}
Xcode: Version 12.0.1
iOS: 14.0
Life Cycle: SwiftUI App
Upvotes: 4
Views: 960