Swift - 在特定时间处理和通知



我需要指示如何执行以下过程。我已经寻找了一些方法,但我没有找到任何我想要的方法。

我有一个带有本地数据库的应用程序。我希望每天在特定时间让应用程序读取客户端并发送本地通知,通知谁将过生日。

如何使此过程在后台和前台同时工作?我还需要它在特定时间运行。

我需要创建一个在后台运行的进程,并且无论应用程序的状态如何,都计划在特定时间运行。

首先,导入用户通知

import UserNotifications

然后添加以下函数来定义通知的内容:

func notification(month: Int, day: Int, hour: Int, minute: Int, text: String){
let content = UNMutableNotificationContent()
content.title = "Put your title Here (birthday)"
//or you can assign it a parameter like text so you can have a different title for each notification
content.body = text
content.sound = UNNotificationSound.default
let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(month: month, day: day, hour: hour, minute: minute), repeats: true)
let request = UNNotificationRequest(identifier: text, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

在视图中确实使用以下代码加载请求:

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
}

然后,您可以为一年中的某一天创建通知(重复( 我建议做一个..循环,就像我在下面所做的那样

这是您可以循环

播放的所有时间的模板
for x in 1...12 { 
for y in 0...30 {
//(you can find a way to check if 30, 31, or 28 based on x, but for now I'll just do 30)

notification(month: x, day: y, hour: 10, minute: 00, text: "here you read birthdays from your source and put them in text, you can use x and y to access current month and day")

}
}

顺便说一下,无论应用程序的状态如何,这些通知都将运行

最新更新