更改 Swift 中的本地通知文本

Change text of local notification in Swift

我为学生开发了一个应用程序。他可以制定自己的时间表。 我试图创建一个通知,说明第二天如何总结。所以我需要更改文本通知,我该怎么做?

再比如,学生可以写作业。前一天return作业,通知他。

我已经尝试过做一个简单的通知,但是通知的文本是静态的。

let content = UNMutableNotificationContent()                    
content.title = "Changement de semaine"                         
content.body = "Nous sommes en semaine \(notificationSemaineAB())"     
content.sound = UNNotificationSound.default                   

var dateComponent = DateComponents()
dateComponent.weekday = 2
dateComponent.hour = 11

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

let request = UNNotificationRequest(identifier: "semaineAB", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)

对于这个,我希望每个星期的通知文本都告诉我我们是在偶数周还是奇数周。但是在输出中,我总是有相同的文本。

您可以使用此代码删除旧通知

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers:["semaineAB"])

之后,您可以重新使用您的代码来创建新代码。

您可以创建一个扩展 UNMutableNotificationContent 的自定义 class。那将根据even/odd周确定通知的内容。然后,您可以使用另一个 class 来实例化通知请求,使用类型为 UNMutableNotificationContent 的 class 方法。

我会使用单独的 class 来处理所有通知功能

  • 首先创建一个函数,它在你的通知中接受一个字符串Class
  • 然后使用布尔值检查 ViewController
  • 中的偶数周和奇数周
  • 还有一个函数来放置 even/odd 周
  • 的逻辑

在Notifications.swift

class Notifications: NSObjcet, UNUserNotificationCenterDelegate {

func weekTrigger(bodyText: String) {

let content = UNMutableNotificationContent() 

content.body = bodyText

let request = .......// 
}

现在在你的 ViewController

class ViewController: UIViewController {

var aBoolToCheckBtwnEvenOrOddWeek: Bool  //you can set an initial value

let notificationManager = Notifications()

}

在 VC 中您认为合适的地方添加逻辑以在偶数周和奇数周之间进行检查

func someFunction() {

if aBoolToCheckBtwnEvenOrOddWeek == true {   // which means even in my case

notificationManager.weekTrigger(bodyText: evenWeekString) // call the function 

} else {

notificationManager.weekTrigger(bodyText: oddWeekString)

}
}

现在在 ViewController 中的任意位置添加此功能!

快乐编码:]