gpt4 book ai didi

swift - 每天都有不同正文的本地通知

转载 作者:行者123 更新时间:2023-11-30 10:33:16 25 4
gpt4 key购买 nike

我的目标是建立一个应该每天触发的本地通知。通知正文每天都应该不同。这是一个字符串数组,其中的一个字符串应显示在通知中。字符串是随机选择的还是按照数组排序的顺序选择并不重要。

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
}
})
}

}

帮助会很棒。感谢您提供的每一个有用的答案此致告诉又名。雷尔伯特

最佳答案

我知道这已经过时了,但目前,执行此操作的方法是创建多个通知请求(另外,不要将触发器的重复设置为 true)。然后当用户打开应用程序时设置新的。大卫·肖邦的建议(理论上)应该有效,但行不通。

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)
}

关于swift - 每天都有不同正文的本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58631307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com