Is it possible to get better than 16 millisecond response when two uibuttons are pressed at 1 millisecond later? I did this in Android not problem.

mport UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

}

weak var timer: Timer?

var startTime: Double = 0

var time: Double = 0

@IBOutlet weak var timeValueLabel1: UILabel!

@IBOutlet weak var timeValueLabel: UILabel!

@IBAction func stop1Button() {

let timeString = String(format: "%.3f", time)

timeValueLabel1.text = timeString

}

@IBAction func stopButton() {

let timeString = String(format: "%.3f", time)

timeValueLabel.text = timeString

}

override func viewDidAppear(_ animated: Bool) {

startTime = Date().timeIntervalSinceReferenceDate

timer = Timer.scheduledTimer(timeInterval: 0.001,

target: self,

selector: #selector(advanceTimer(timer:)),

userInfo: nil,

repeats: true)

}

override func viewWillDisappear(_ animated: Bool) {

timer?.invalidate()

}

func advanceTimer(timer: Timer) {

time = Date().timeIntervalSinceReferenceDate - startTime

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

/

}

}

Replies

Either I’m missing something important or everything to do with your

time
property is pointless. Having a timer run every millisecond to update
time
is extremely wasteful if all you need is accurate timestamps. You could just implement your
time
property as follows:
var time: Double {
    return Date().timeIntervalSinceReferenceDate - self.startTime
}

In terms of the 16 millisecond delay, that’s likely to be related to how UIKit tracks touches at this high-level. If you want to do this more accurately it’s likely you’re going to want to track touches yourself. This is way outside of my area of expertise but there was a really good talk about it at last year’s WWDC (WWDC 2016 Session 220 Leveraging Touch Input on iOS). You if have follow-up questions about touch handling I recommend you post them to the App Frameworks > Cocoa Touch topic area, because the sticking point here isn’t low-level thread scheduling and so on but UIKit itself.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"