Attempt to refresh live activity with background refreshes

release
Laurent 3 years ago
parent f5067feb99
commit 16fbfa1d65
  1. 50
      LeCountdown/Conductor.swift
  2. 2
      LeCountdown/CountdownScheduler.swift
  3. 5
      LeCountdown/Info.plist
  4. 28
      LeCountdown/LeCountdownApp.swift

@ -7,6 +7,7 @@
import Foundation import Foundation
import ActivityKit import ActivityKit
import BackgroundTasks
class Conductor : ObservableObject { class Conductor : ObservableObject {
@ -49,12 +50,12 @@ class Conductor : ObservableObject {
if !cancel { if !cancel {
self._recordActivity(countdownId: countdownId) self._recordActivity(countdownId: countdownId)
} }
self.notificationDates.removeValue(forKey: countdownId)
// self._updateLiveActivity(countdownId: countdownId, endDate: <#T##Date#>) if self.notificationDates.removeValue(forKey: countdownId) != nil {
self._endLiveActivity(countdownId: countdownId) self._endLiveActivity(countdownId: countdownId)
} }
} }
}
func cleanup() { func cleanup() {
let now = Date() let now = Date()
@ -114,11 +115,25 @@ class Conductor : ObservableObject {
do { do {
let liveActivity = try ActivityKit.Activity.request(attributes: attributes, content: activityContent) let liveActivity = try ActivityKit.Activity.request(attributes: attributes, content: activityContent)
print("Requested a countdown Live Activity \(String(describing: liveActivity.id)).") print("Requested a Countdown Live Activity: \(String(describing: liveActivity.id)).")
} catch (let error) { } catch (let error) {
print("Error requesting countdown Live Activity \(error.localizedDescription).") print("Error requesting countdown Live Activity \(error.localizedDescription).")
} }
self._scheduleAppRefresh(countdown: countdown)
}
}
fileprivate func _scheduleAppRefresh(countdown: Countdown) {
let request = BGAppRefreshTaskRequest(identifier: BGTaskIdentifier.refresh.rawValue)
request.earliestBeginDate = Date(timeIntervalSinceNow: countdown.duration)
do {
try BGTaskScheduler.shared.submit(request)
print("request submitted with date: \(String(describing: request.earliestBeginDate))")
} catch {
print("Could not schedule app refresh: \(error)")
} }
} }
@ -127,25 +142,36 @@ class Conductor : ObservableObject {
} }
func updateLiveActivities() { func updateLiveActivities() {
print("update live activity...")
for (countdownId, interval) in self.notificationDates { for (countdownId, interval) in self.notificationDates {
if let activity = self._liveActivity(countdownId: countdownId) {
Task { if interval.end < Date() {
let ended = interval.end < Date() self._endLiveActivity(countdownId: countdownId)
let state = LaunchWidgetAttributes.ContentState(ended: ended)
let content = ActivityContent(state: state, staleDate: interval.end)
await activity.update(content)
print("Ending the Live Activity: \(activity.id)")
}
} }
// if let activity = self._liveActivity(countdownId: countdownId) {
//
// Task {
//
// if ended {
// self._endLiveActivity(countdownId: countdownId)
// }
//
//// let state = LaunchWidgetAttributes.ContentState(ended: ended)
//// let content = ActivityContent(state: state, staleDate: interval.end)
//// await activity.update(content)
//// print("Ending the Live Activity: \(activity.id)")
// }
// }
} }
} }
fileprivate func _endLiveActivity(countdownId: String) { fileprivate func _endLiveActivity(countdownId: String) {
print("Trt to end the Live Activity: \(countdownId)") print("Try to end the Live Activity: \(countdownId)")
if let activity = self._liveActivity(countdownId: countdownId) { if let activity = self._liveActivity(countdownId: countdownId) {
Task { Task {

@ -53,7 +53,7 @@ class CountdownScheduler {
let duration = countdown.duration let duration = countdown.duration
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: duration + offset, repeats: false) let trigger = UNTimeIntervalNotificationTrigger(timeInterval: duration + offset, repeats: false)
let request = UNNotificationRequest(identifier: countdown.objectID.uriRepresentation().absoluteString + "/\(offset)", let request = UNNotificationRequest(identifier: countdown.objectID.uriRepresentation().absoluteString,
content: content, content: content,
trigger: trigger) trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in UNUserNotificationCenter.current().add(request) { error in

@ -2,6 +2,10 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>com.staxriver.lecountdown.refresh</string>
</array>
<key>NSUserActivityTypes</key> <key>NSUserActivityTypes</key>
<array> <array>
<string>SelectCountdownIntent</string> <string>SelectCountdownIntent</string>
@ -16,6 +20,7 @@
<key>UIBackgroundModes</key> <key>UIBackgroundModes</key>
<array> <array>
<string>audio</string> <string>audio</string>
<string>fetch</string>
</array> </array>
</dict> </dict>
</plist> </plist>

@ -6,6 +6,11 @@
// //
import SwiftUI import SwiftUI
import BackgroundTasks
enum BGTaskIdentifier : String {
case refresh = "com.staxriver.lecountdown.refresh"
}
@main @main
struct LeCountdownApp: App { struct LeCountdownApp: App {
@ -32,6 +37,8 @@ struct LeCountdownApp: App {
} }
fileprivate func _onAppear() { fileprivate func _onAppear() {
self._registerBackgroundRefreshes()
// Task { // Task {
// for s in Sound.allCases { // for s in Sound.allCases {
// do { // do {
@ -44,4 +51,25 @@ struct LeCountdownApp: App {
// } // }
} }
fileprivate func _registerBackgroundRefreshes() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: BGTaskIdentifier.refresh.rawValue, using: nil) { task in
self._handleAppRefresh(task: task as! BGAppRefreshTask)
}
}
fileprivate func _handleAppRefresh(task: BGAppRefreshTask) {
print("_handleAppRefresh = \(task.description)")
task.expirationHandler = {
print("expired")
}
DispatchQueue.main.async {
Conductor.maestro.updateLiveActivities()
task.setTaskCompleted(success: true)
}
}
} }

Loading…
Cancel
Save