新的Xcode和Swift。我的应用程序有一个倒计时器。我希望倒计时作为一个通知从锁屏可见,但我不知道如何(如果它甚至可能)更新现有的本地通知的内容。
到目前为止,我找到的唯一解决方案是取消当前通知,每秒显示一个新通知,这并不理想。
代码:
struct TimerApp: View {
private let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
@State private var isActive: Bool = true // whether not timer is active
@State private var timeRemaining: Int = 600 // 60 seconds * 10 mins = 10 min-countdown timer
var body: some View {
// body stuff
// toggle isActive if user stops/starts timer
}.onReceive(timer, perform: { _ in
guard isActive else { return }
if timeRemaining > 0 {
// would like to update current notification here
// *******
// instead, removing and adding a new one right now
UNUserNotificationCenter.current().removeAllDeliveredNotifications()
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
addNotification()
timeRemaining -= 1
} else {
isActive = false
timeRemaining = 0
}
}
func addNotification() {
let center = UNUserNotificationCenter.current()
let addRequest = {
let content = UNMutableNotificationContent()
content.title = "App Title"
content.body = "Time: \(timeFormatted())"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.0001, repeats: false)
let request = UNNotificationRequest(identifier: "onlyNotification", content: content, trigger: trigger)
center.add(request)
}
center.getNotificationSettings { settings in
if settings.authorizationStatus == .authorized {
addRequest()
} else {
center.requestAuthorization(options: [.alert, .badge]) { success, error in
if success {
addRequest()
} else if let error = error {
print("error :( \(error.localizedDescription)")
}
}
}
}
}
func timeFormatted() -> String {
// converts timeRemaining to 00:00 format and returns string
}
}
这就是现在这个可笑的糟糕解决方案。
1条答案
按热度按时间r3i60tvu1#
目前无法更新挂起或已发送的本地通知请求。
正如您所猜测的那样,为了传递具有不同内容的通知,您需要使用
UNNotificationCenter
的方法removePendingNotificationRequests(withIdentifiers:)
或removeAllPendingNotificationRequests()
删除挂起的请求,并添加具有更新内容的新请求。