2

How to count time while phone is shaking in swift? want to get time measurement how long phone is shaking.

var timer = Timer()
var timeLeft = 0

override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if(motion == .motionShake){
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
    }
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if(motion != .motionShake){
        print("MotionEnded")
        timer.invalidate()
    }
}

The timer is working endlessly. How to stop the timer when shaking stop...​

Mika Dior
  • 53
  • 8

3 Answers3

1

To measure the timeInterval between the shaking start time and end time using,

var startDate: Date?

override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if(motion == .motionShake){
        self.startDate = Date()
    }
}

override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if(motion != .motionShake){
        if let startDate = self.startDate {
            let timeInterval = Date().timeIntervalSince(startDate)
            print(timeInterval)
        }
    }
}

In the above code, I've stored the Date instance at which motion begins and when the motion ends timeInterval is calculated using the current date and the stored date.

PGDev
  • 23,751
  • 6
  • 34
  • 88
  • `UIEvent` has a `timestamp` field, you can use that and save yourself the calls to `Date` – idz May 24 '19 at 09:35
0

Tested on a real device :

  var startShaking = CFAbsoluteTimeGetCurrent()

  override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
      startShaking = CFAbsoluteTimeGetCurrent()
    }
  }

  override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
      let shakingTime = CFAbsoluteTimeGetCurrent() - startShaking
      print("shaking for \(shakingTime) seconds")
    }
  }
TagTaco
  • 143
  • 5
0

Try below code : Here the startDate is the timestamp when the shaking is started.

override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        startDate = Date()
        print("Motion begins")
    }

    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        print("Motion ends")
        let endDate = Date()
        let difference = Calendar.current.dateComponents([.hour, .minute, .second, .nanosecond], from: startDate!, to: endDate)
        let formattedString = String(format: "%02ld %02ld %02ld %02ld", difference.hour!, difference.minute!, difference.second!, difference.nanosecond!)
        print(formattedString)
    }

The output will print the time difference in hour, minutes, seconds and nano seconds.

Hope this helps.

BhargavR
  • 1,095
  • 7
  • 14