How to make a timer with 0.1 millisecond accuracy

I have tried to add a timer in a drawing app so that it can track the time of the drawing. When the user starts drawing(touches begin), the timer starts to time. Then when the user lifts the pen or finger, the timer stops. I wanted to have the accuracy of the timer to be 0.1seconds.

Following are the code I have tried but can only have 1 as the smallest internal.

@objc func startTiming () {
         time += 1.0
     }
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    //start timing
    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(TrailingCanvas.startTiming), userInfo: nil, repeats: true)
    let touch = touches.first
    startingPoint = touch?.preciseLocation(in: self)
    TrailUserInputX.append(startingPoint.x)
    TrailUserInputY.append(startingPoint.y)
    print("\(String(describing: touch?.force))")
    }
    
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    //timer
    timer.invalidate()
    endingPointX = TrailUserInputX.last
    if endingPointX != nil {
        UserMatchingLocation.append(endingPointX!)
    }
}

@feanor Do you still have issues with this?

No thanks, I have also fixed this. Thanks for asking though.

By comparing the .timestamp properties on the two events? I hope your solution doesn’t involve counting the passage of time, but instead computes the delta between two instants in time.

1 Like

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