Search code examples
macosswiftbackground-processalarm

How do I run an alarm from user input in swift


So far I have created a loop that takes a user input and compares it to the current time, and sounds an alarm if there is a match. When I run this it runs at 99% CPU usage and makes my computer nearly unusable. I am looking for a way to run this on a much lower priority or better yet, an alternative to a loop. All the other answers I have seen either don't address the user input through text, or isn't in swift. Any help is much appreciated and below is the function that compares the two times, the alarmHour and alarmMinute variables are the ones that the user enters.

func runTimer() {
    var rightTime:Bool
    do {
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
        let hour = String(components.hour)
        let minutes = String(components.minute)
        if (hour == globe.alarmHour && minutes == globe.alarmMinutes){
            rightTime = true
        } else {
            rightTime = false
        }
    } while (rightTime == false)
    if (rightTime == true) {
        prepareAudio()
        AlarmSound.play()
    }

}

Solution

  • Ugh. Your do/while loop is in fact a very bad way to do it for the reasons you've outlined.

    In most cases an NSTimer is the way to go. Take a look at the 'scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:` method.

    You create a timer and schedule it and it calls your selector at the desired time.

    NSTimers aren't totally exact. They can be off by around 50ms, but for displaying an alarm to the user that's fine.