【发布时间】:2023-01-05 18:49:20
【问题描述】:
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
}
}
这就是现在最糟糕的解决方案的样子。
【问题讨论】:
-
您可能想查看新的锁定屏幕小部件,它们可能会提供更好的解决方案。我认为不可能修改通知。
-
会做的,谢谢你的提示!