要实现本地通知与倒计时功能,可以使用以下步骤:
导入相关的库
import UIKit
import UserNotifications
请求用户授权通知权限
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
print("用户授权通知权限")
}
}
创建本地通知
func createLocalNotification(withTitle title: String, andBody body: String, afterDelay delay: TimeInterval) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: delay, repeats: false)
let request = UNNotificationRequest(identifier: "LocalNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("创建本地通知失败:\(error.localizedDescription)")
}
}
}
创建倒计时功能
var countdownTimer: Timer?
var remainingTime = 60
func startCountdown() {
countdownTimer?.invalidate()
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)
}
@objc func updateCountdown() {
if remainingTime > 0 {
remainingTime -= 1
print("倒计时剩余时间:\(remainingTime)")
} else {
countdownTimer?.invalidate()
print("倒计时结束")
}
}
调用上述方法
// 创建本地通知并在5秒后发送
createLocalNotification(withTitle: "本地通知", andBody: "这是一个本地通知示例", afterDelay: 5)
// 启动倒计时
startCountdown()
上述代码示例了如何创建本地通知并在指定的延迟时间后发送,以及如何创建一个倒计时功能。你可以根据自己的需求进行修改和扩展。
上一篇:本地通知与操作按钮
下一篇:本地通知与FCM:哪一个更合适?