I’m looking to update the app icon badge count for an iOS app in the background, while the app is not in use. The twist here is that the badge count does not depend upon external events and push notifications, as most of the examples I’ve found online do. Instead, the badge count should silently update based upon the relationship between the underlying SwiftData and the passage of time. I’m struggling to figure out how to query SwiftData in a .backgroundTask in an App file.
Here’s an example based upon the default code when a user opens a new Xcode project that uses SwiftUI, SwiftData, and is hosted in CloudKit. The first code block works but requires the user to open the app in order to update the app icon badge count:
struct ContentView: View {
@Environment(.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
NavigationSplitView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at (item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
.onAppear() {
updateBadgeNumber()
}
} detail: {
Text("Select an item")
}
}
func updateBadgeNumber() {
let now = Date()
let pastWeek = Calendar.current.date(byAdding: .day, value: -7, to: now)
let badgeNumber = items.filter{ $0.timestamp >= pastWeek!}.count
UNUserNotificationCenter.current().setBadgeCount(badgeNumber)
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
}
And this code indicates the kind of approach I think I probably need, using BackgroundTasks, but I’m stuck on the @Query line in the updateIconBadge() function:
import SwiftUI
import SwiftData
import BackgroundTasks
@main
struct BadgeNumberExampleApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self,
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: (error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
.backgroundTask(.appRefresh("UpdateBadge")) {
scheduleAppRefresh()
updateIconBadge()
} // End of .backgroundTask(.appRefresh("UpdateBadge"))
}
}
func updateIconBadge() {
@Query var items: [Item]
let now = Date()
let pastWeek = Calendar.current.date(byAdding: .day, value: -7, to: now)
let badgeNumber = items.filter{ $0.timestamp >= pastWeek!}.count
UNUserNotificationCenter.current().setBadgeCount(badgeNumber)
}
func scheduleAppRefresh() {
let today = Calendar.current.startOfDay(for: .now)
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)!
let timeComponent = DateComponents(hour: 0)
let refreshTime = Calendar.current.date(byAdding: timeComponent, to: tomorrow)
let request = BGAppRefreshTaskRequest(identifier: "UpdateBadge")
request.earliestBeginDate = refreshTime
try? BGTaskScheduler.shared.submit(request)
}