代码之家  ›  专栏  ›  技术社区  ›  Shi Zhang

持续设置新的本地通知-ios

  •  0
  • Shi Zhang  · 技术社区  · 7 年前

    我正在模拟警报。

    为了做到这一点,我尝试在某些条件为真时每X秒发送一次新的本地通知,并在某些条件为假时停止(当用户取消警报时)

    我有一个 Set 按钮和a Stop 按钮

    以下代码用于 设置 按下按钮:

    @IBAction func setNotification(_ sender: Any) {
    //        timeEntered = time.text!
    //        let hrMin = timeEntered.components(separatedBy: ":");
            let content = UNMutableNotificationContent()
            content.title = "How many days are there in one year"
            content.subtitle = "Do you know?"
            content.body = "Do you really know?"
            content.badge = 1
            content.sound = UNNotificationSound(named: "alarm.aiff");
    
            while (repeatNotifications) {
                trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false);
    
                let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
    
                UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
            }
    }
    

    停止

    @IBAction func stopRepeat(_ sender: Any) {
        repeatNotifications = false
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }
    

    现在,当我按下 设置 按钮,它卡在按下模式下(颜色变化),我不能按任何其他按钮(即: 停止 按钮)。此外,没有设置本地通知。

    有没有办法做到这一点?

    tl;dr:如何每隔X秒设置一次新的本地通知,直到按下某个按钮为止

    1 回复  |  直到 7 年前
        1
  •  4
  •   MD Aslam Ansari    7 年前

    你的while状态比你想象的运行得更快。它可能会通过创建大量对象来阻塞通知类。请使用计时器每5秒运行一次以推送通知。 您可以使用 仪器工具 看看问题所在。