Swift定时发送本地通知(Local Notification)

0 阅读1分钟
  1. 引入UserNotifications

import UserNotifications

  1. 获取通知权限
let notificationCenter = UNUserNotificationCenter.current()
 
do {
        try await notificationCenter.requestAuthorization(options:[.alert, .sound, .badge])
} catch {
         //Handle errors that may occur during add.处理错误
         fatalError("Could not turn on notification: \(error)")
}
  1. 添加本地通知
let content = UNMutableNotificationContent()
//通知的标题、内容和提示音
content.title =Hello, Sweetie”
content.body =Best wishes for you.“
content.sound = UNNotificationSound.default

//通知的时间是每天12:30
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = 12
dateComponents.minute = 30

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

//如果是每隔一段时间提醒一次,可以写下面的trigger,实现每10秒提醒一次
//let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: true)

let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)

let notificationCenter = UNUserNotificationCenter.current()

notificationCenter.add(request)
  1. 踩坑提示:这个通知默认是你的app在后台运行时,它才会显示,所以测试时记得先退出app,否则看不到效果......