# Play sound when countdown date is reached

**URL:** <https://forums.kodeco.com/t/play-sound-when-countdown-date-is-reached/30980>\
**Category:** Swift\
**Created:** [June 15, 2017, 4:45pm UTC](https://forums.kodeco.com/t/play-sound-when-countdown-date-is-reached/30980 "2017-06-15T16:45:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![zalubski](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/zalubski/32/81494_2.png) [@zalubski](https://forums.kodeco.com/u/zalubski)\
**Post date:** [June 15, 2017, 4:45pm UTC](https://forums.kodeco.com/t/play-sound-when-countdown-date-is-reached/30980/1 "2017-06-15T16:45:03Z")

</div>

The following code is a countdown clock to Christmas. All I want to do is when the endTime is reached is to play a mp3 file. I think to to do there you would have to make a if else statement on timeDifference and I tried that but it did not work. What I want to do is play the sound once with no repeat when the “endTime” is reached.

```
                    import UIKit

     class ViewController: UIViewController {

    @IBOutlet var displayLabel: UILabel!

    let formatter = DateFormatter()
     let userCleander = Calendar.current;
   let requestedComponent : Set<Calendar.Component> = [
     Calendar.Component.month,
Calendar.Component.day,
Calendar.Component.hour,
Calendar.Component.minute,
Calendar.Component.second
    ]

    override func viewDidLoad() {
super.viewDidLoad()

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timePrinter), userInfo: nil, repeats: true)

timer.fire()
    }

    func timeCalculator(dateFormat: String, endTime: String, startTime: Date = Date()) -> DateComponents {
 formatter.dateFormat = dateFormat
let _startTime = startTime

let _endTime = formatter.date(from: endTime)

let timeDifference = userCleander.dateComponents(requestedComponent, from: _startTime, to: _endTime!)
return timeDifference

    }

  func timePrinter() -> Void {
      let time = timeCalculator(dateFormat: "MM/dd/yyyy hh:mm:ss a", endTime: "6/14/2017 10:39:00 p")
displayLabel.text = "\(time.month!) Months \(time.day!) Days \(time.minute!) Minutes \(time.second!) Seconds"
    }}

```

---

<div class="post-metadata">

**Author:** ![nikita\_gaydukov](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/nikita_gaydukov/32/77683_2.png) [@nikita\_gaydukov](https://forums.kodeco.com/u/nikita_gaydukov)\
**Post date:** [July 2, 2017, 12:22pm UTC](https://forums.kodeco.com/t/play-sound-when-countdown-date-is-reached/30980/2 "2017-07-02T12:22:49Z")

</div>

Hi @zalubski

You are correct, you will need an “if” statement in your “timeCalculator” function. Also you need to invalidate the timer in order to stop receiving timer update callbacks. Like this:  
`Timer.invalidate()`  
Let me know if this helps.

Nikita
