如何在iOS中安排可以暂停或删除的本地通知?

时间:2016-07-28 22:33:11

标签: ios swift notifications uilocalnotification localnotification

我正在尝试使用以下iOS库实现本地前台通知:https://github.com/kunass2/BSForegroundNotification

我希望在倒计时达到0后触发通知,但是我找不到在计时器上实现暂停和重启按钮的好方法,该按钮还会暂停通知或设置新通知。

这是我当前的实现,但失败了,因为如果我按下重启意图启用重置计时器的新通知,则旧的通知也会被触发:

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)
}

1 个答案:

答案 0 :(得分:0)

我通过在App Delegate中实现didReceiveLocalNotification()方法来修复此问题,以显示前景通知。