Search code examples
iosswiftbackground-process

Using UIApplicationDidEnterBackgroundNotification flag


I call the function below using an NSTimer, and I want that when the countdown is done, a sound is triggered. I managed to do both in active mode and background using the codes below. Now I wanted to wrap them in a if statement, which depends on the app state but it always triggers the else part.

func CountDown() {

    Timer  -= 1

    CountDownLabel.text = MakeTimeLabel()
    ProgressCircle.strokeEnd = 1-(CGFloat(Timer/Test))

    if Timer == -1 {

        if UIApplicationDidEnterBackgroundNotification == true {

        let soundnotification = UILocalNotification()

        soundnotification.soundName = "Boxing.wav"

        UIApplication.sharedApplication().scheduleLocalNotification(soundnotification)

        println("timer is done in background mode")

        } else {

        // Load Sound
        soundlocation = NSBundle.mainBundle().URLForResource("Boxing", withExtension: "wav")!

        player = AVAudioPlayer(contentsOfURL: soundlocation, error: &Error)
        player.volume = 1 

        // Play Sound
        player.play()

        println("timer is done in active mode")

        }

        StopButton(self)

    }   
}

Thanks in advance


Solution

  • This is because you are comparing String "UIApplicationDidEnterBackgroundNotification" with Boolean value "true". This will always be evaluated "false".

    I believe you need to compare:

    UIApplication.sharedApplication().applicationState == UIApplicationState.Background