【发布时间】:2020-06-05 13:11:11
【问题描述】:
当我点击按钮时,它应该每 90 秒从我的数组中发送一个随机元素。 但它总是发送相同的。 例如,第一个 Notifications 是一个“A”,所有其他 Notifications 也是一个 A。 但我希望它们是数组中的随机数,我也希望可以将实际的 randomElement 保存在另一个变量中。
class ViewController: UIViewController {
var meinArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "A", "B", "C", "D"]
override func viewDidLoad() {
super.viewDidLoad()
authorize()
}
@IBAction func button_Tapped(_ sender: UIButton) {
if let random = meinArray.randomElement(){
addNotification(time: 90, body: random)
}
}
let uncenter = UNUserNotificationCenter.current()
func authorize(){
uncenter.requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in
print(error ?? "No error")
}
configure()
}
func configure(){
uncenter.delegate = self
}
func addNotification(time: TimeInterval, body: String){
let content = UNMutableNotificationContent()
content.body = body
content.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: time, repeats: true)
let request = UNNotificationRequest(identifier: "request", content: content, trigger: trigger)
uncenter.add(request, withCompletionHandler: nil)
}
}
【问题讨论】:
标签: swift xcode notifications nstimeinterval