【问题标题】:Random Element from Array with repeating TimeIntervalNotificationTrigger具有重复 TimeIntervalNotificationTrigger 的数组中的随机元素
【发布时间】: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


    【解决方案1】:

    试试这个:

    @IBAction func button_Tapped(_ sender: UIButton) {
        Timer.scheduledTimer(timeInterval: 90, target: self, selector: #selector(showArray), userInfo: nil, repeats: true)
    }
    
    @objc func showArray() {
        if let random = meinArray.randomElement() {
            let content = UNMutableNotificationContent()
            content.body = random
            content.sound = .default
    
            let request = UNNotificationRequest(identifier: "request", content: content, trigger: nil)
    
            uncenter.add(request, withCompletionHandler: nil)
        }
    }
    

    ...

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler( [.alert, .badge, .sound])
    }
    

    看起来像我们这样做:

    if let random = meinArray.randomElement(){
        addNotification(time: 90, body: random)
    }
    

    然后添加到 NotificationCenter,回调将不会再次运行 .randomElement(),而是只会获取第一个元素并且只调用它。

    【讨论】:

    • 嘿,我必须回答我的问题,因为代码太长了。它不工作.. :(请看我的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2016-05-15
    相关资源
    最近更新 更多