使用计时器每X秒设置本地通知

我试图通过设置新的本地通知每隔X秒,当一个Setbutton被按下,当用户点击一个Stopbutton时停止报警应用程序。

使用Timer() ,我目前能够设置本地通知,但它不会重复,因为我想。 它只是当我进入应用程序,并通过Homebutton回到前一个屏幕时,重复。 而且,这样做只能重复一次。

有什么办法可以让用户只按一下Setbutton,不pipe你是在应用程序中还是在应用程序之外,只有当用户按下Stopbutton时,才会停止通知?

我的代码如下:

 class LocalNotificationViewController: UIViewController { var timer = Timer() func runTimer() { timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: (#selector(self.setLocalNotification)), userInfo: nil, repeats: true) } @objc func setLocalNotification() { // timeEntered = time.text! // let hrMin = timeEntered.components(separatedBy: ":"); let content = UNMutableNotificationContent() content.title = "Test Local Notification" content.subtitle = "Testing..." content.body = "Testing..." content.badge = 1 content.sound = UNNotificationSound(named: "alarm.aiff"); trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false); let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } var timeEntered: String = ""; var trigger: UNTimeIntervalNotificationTrigger? = nil; @IBOutlet var time: UITextField!; @IBAction func setNotification(_ sender: Any) { runTimer() } @IBAction func stopRepeat(_ sender: Any) { timer.invalidate() }