Search code examples
iosswiftiphoneuitouch

Swift: record touch force, size, duration


For a data analysis project, I want to track the measurements for touch force, size and duration in a log-file for a simple app (I use the Foodtracker app from the Apple Documentation Website).

I know that I can get the force, size and duration from UITouch. But

  1. how do I access UITouch to get these measurements?
  2. and how do I write these measurements into a log-file?

Solution

  • 1. How do I access UITouch to get these measurements?

    You'll have to override the touch handlers in your view controller.

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        let touch = touches.first!
        print("\(touch.force)")
        print("\(touch.majorRadius)")
        print("\(touch.timestamp)")
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        let touch = touches.first!
        print("\(touch.force)")
        print("\(touch.majorRadius)")
        print("\(touch.timestamp)")
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesCancelled(touches, with: event)
        let touch = touches.first!
        print("\(touch.force)")
        print("\(touch.majorRadius)")
        print("\(touch.timestamp)")
    }
    

    2. How do I write these measurements into a log-file?

    For that checkout this post: Read and write a String from text file