我的目标是建立每天都会触发的本地通知。通知主体应该每天都不同。 这是字符串数组,在通知中应显示一个字符串。 随机选择字符串还是按顺序排列数组都没关系。
var arrayText: [String] = ["text1",
"text2",
"text3",
"text4",
"text5"]
这就是我走了多远。只是带有相同正文文本的普通本地通知。
func scheduleNotifications()
{
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
if !granted {
print("Something went wrong")
}
}
let content = UNMutableNotificationContent()
content.title = "Test"
content.body = "test"
content.sound = UNNotificationSound.default
let gregorian = Calendar(identifier: .gregorian)
let now = Date()
var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)
components.hour = 18
components.minute = 42
components.second = 10
let date = gregorian.date(from: components)!
let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
}
})
}
}
帮助会很棒。并感谢您的每一个有用的回答 此致 告诉阿卡Relbot
答案 0 :(得分:0)
只需将content.body = "test"
更改为content.body = arrayText[Int(arc4random_uniform(5))]
。这样可以使content.body
等于arrayText
中的随机元素。
答案 1 :(得分:0)
我知道这很旧,但是目前,执行此操作的方法是创建多个通知请求(也不要将触发器的重复设置为true)。然后在用户打开应用程序时设置新的。大卫·肖邦(David Chopin)提出的建议,在理论上应该起作用,但不起作用。
let array = ["text1", "text2", "text3", "text4", "text5"]
let chosenDate = Date()
for item in 0...64 {
let date = chosenDate.adding(Calendar.Component.day, value: item)
let triggerDaily = Calendar.current.dateComponents([.day, .hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: false)
let text = self.getRandom() {
let content = UNMutableNotificationContent()
content.body = array[Int(arc4random_uniform(UInt32(array.count)))]
content.sound = UNNotificationSound.default
let request = UNNotificationRequest(identifier: quote.id!, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}