Run loop based intervals playing sound swift4

I want to make a app that plays a sound based on intervals that the user enters. So say if the user enters 2 times per 10 seconds. The sound should play at 5 seconds and 10 seconds.

               import UIKit
class ViewController: UIViewController {
@IBOutlet var playbutton: UIButton!
@IBOutlet var titlelabel: UILabel!
@IBOutlet var judo: UITextField!
 @IBOutlet var judo2: UITextField!
 var timer : Timer?
 var counter = 0.0
var isRunning = false
override func viewDidLoad() {
titlelabel.text = "\(counter)"
playbutton.isEnabled = true
 @IBAction func btnplay(_ sender: UIButton) {
if timer == nil {
    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(UpdateTime), userInfo: nil, repeats: true)
    playbutton.isEnabled = false
@objc func UpdateTime(){
counter += 0.1
titlelabel.text = String(format: "%.1f", counter)
let numberOfTimes = Double(judo.text ?? "") ?? 0.0
 let maxTime = Double(judo2.text ?? "") ?? 0.0
if counter >= maxTime {

    timer = nil

  if counter <= maxTime {
    ////RUN LOOP

Hi @timswift,
hope your projects are progressing, good to see you with a newer issue.

You have the right idea on how to solve this issue. Is there a specific reason why you want to count by yourself in each timer event?

There are a couple of things you must bear in mind when trying to use timers,

  1. Timers are not High-resolution
  2. Timers do not return till the code in the event handler is executed completely

with that in mind, you are better off getting an event at the time interval you want than trying to calculate the ticks yourself.



What do you mean by high resolution.

Hi @timswift,
TLDR; timers that offer you finer granularity and accuracy are called High-resolution timers. Here’s more reading in case you want Technical Note TN2169: High Precision Timers in iOS / OS X



This topic was automatically closed after 166 days. New replies are no longer allowed.