我的目标是建立一个每天触发的本地通知。通知主体应该每天都不同。这是字符串数组,在通知中应显示一个字符串。随机选择字符串还是按顺序排列数组都没关系。
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
仅将content.body = "test"
更改为content.body = arrayText[Int(arc4random_uniform(5))]
。这样就可以使content.body
等于arrayText
中的随机元素。