背景中的重复本地通知(番茄钟定时器)

时间:2016-07-28 19:59:46

标签: ios swift notifications local uilocalnotification

我正在尝试为iOS创建一个Pomodoro计时器,但我在实现后台通知时遇到了麻烦。不幸的是,即使我在后台根据当前计时器中剩余的时间触发通知的代码似乎是正确的,但这个代码永远不会在后台执行,因此只会触发一个本地通知。

定时器在前一个完成后重复切换类型和持续时间:

func countdown() { // gets called by timer every second
        self.timeRemaining = timeRemaining - 1 // decrement timeRemaining integer
        self.updateTimer()
        if self.timeRemaining == 0 {
            AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
        }
        if self.timeRemaining < 0 {
            self.switchTimerType()
            setupLocalNotifications()
        }
        print("counting down")
    }



func switchTimerType() {
    if self.timerType == TimerType.Work {
        self.timerType = TimerType.Break
        self.typeName = "Break"
    }
    else if self.timerType == TimerType.Break {
        self.timerType = TimerType.Work
        self.typeName = "Work"
    }
    setTimeBasedOnTimerType(self.timerType)
    resetTimer()
}


func setTimeBasedOnTimerType(timerType: TimerType) {
        switch timerType {
        case TimerType.Work:
            self.timeMax = Double(self.workTimeMax)
            self.typeName = "Work"

        case TimerType.Break:
            self.timeMax = Double(self.breakTimeMax)
            self.typeName = "Break"
        }
    }

设置当前计时器持续时间的本地通知(不会按预期多次调用):

func setupLocalNotifications() {
        UIApplication.sharedApplication().cancelAllLocalNotifications()
        self.localNotification = UILocalNotification()
        self.localNotificationEndDate = NSDate().dateByAddingTimeInterval(self.timeRemaining)
        print("Current date: \(NSDate())")
        let alertBody = "Time for " + self.typeName + " is up!"
        let alertTitle = ""
        self.localNotification!.fireDate = self.localNotificationEndDate
        self.localNotification!.alertBody = alertBody
        self.localNotification!.alertTitle = alertTitle
        self.localNotification!.soundName = UILocalNotificationDefaultSoundName
        self.localNotification!.category = "START_CATEGORY"

        UIApplication.sharedApplication().scheduleLocalNotification(self.localNotification!)
}

0 个答案:

没有答案