简体   繁体   中英

How to schedule local notifications in iOS that can be paused or removed?

I am trying to implement local foreground notifications with the following iOS library: https://github.com/kunass2/BSForegroundNotification

I want the notification to fire after the countdown reaches 0 , but am having trouble finding a good way to implement pause and restart buttons on the timer that also pauses the notification or sets up a new one.

This is my current implementation, which fails because if I press restart intending to enable firing of the new notification for the reset timer, the old notification is also fired:

func setupLocalNotifications() { // called whenever current timer countdown reaches 0
let notification = BSForegroundNotification(userInfo: userInfoForCategory("ONE_BUTTON"))
    notification.timeToDismissNotification = NSTimeInterval(10)
    // Delay 10 seconds
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(self.timeRemaining * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
        if self.willDisplayForegroundNotification {
            notification.presentNotification()
        }
    }
    notification.delegate = self
}

@IBAction func startPauseButtonPressed(sender: AnyObject) {
        if self.counting {
            self.timer?.invalidate()
            UIApplication.sharedApplication().cancelAllLocalNotifications()
            self.willDisplayForegroundNotification = false
            self.counting = false
            startPauseButton.setTitle("Resume", forState: .Normal)
            startPauseButton.setImage(UIImage(named: "Play.png"), forState: .Normal)
        }
        else {
            setupLocalNotifications()
            self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(NewFocusViewController.countdown), userInfo: nil, repeats: true)
            self.willDisplayForegroundNotification = true
            self.counting = true
            startPauseButton.setTitle("Pause", forState: .Normal)    
        }
}

@IBAction func restartButtonPressed(sender: AnyObject) {
    self.timer?.invalidate()
    UIApplication.sharedApplication().cancelAllLocalNotifications()
    self.timeRemaining = Double(self.timeMax)
    self.counting = false
    self.willDisplayForegroundNotification = false
    self.updateTimer()
    self.startPauseButton.setTitle("Start", forState: .Normal)
}

我通过在App Delegate中实现didReceiveLocalNotification()方法来解决此问题,以呈现前台通知。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM