If user clicks 1 and less than 5 times click/press then OneTimeClickAction
func should called,
If User simultaneously or consecutively 5 times and less than 10 times click/press then FiveTimeClickAction
func should get called
and If User simultaneously or consecutively more than 10 times click/press then tenTimeClickAction
func should get called.
{
guard let tempDate = self.lastTappedAt else { return }
let elapsed = Date().timeIntervalSince(tempDate)
let duration = Int(elapsed)
print(duration)
if duration < 2 {
tapCount = tapCount + 1
// return
} else {
tapCount = 0
}
self.lastTappedAt = Date()
if tapCount > 9 {
let dispatchTime = DispatchTime.now() + 3.0
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.didTappedTenTimes(.happy)
}
return
}
if ((tapCount < 6) && (duration > 2)) {
let dispatchTime = DispatchTime.now() + 3.0
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.didTappedFiveTimes(.react)
}
return
}
if tapCount == 0{
let dispatchTime = DispatchTime.now() + 3.0
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.didTapped(.wink)
}
}
}
please feel free to let me know more about the same in depth and suggest me to deal this in better way.
Thanks
OK, I understand you don't want to track actual time when button is pressed, but only count taps in some reasonable time, assuming multiple taps one after another belonging to same action (wink, happy, react).
var tapCount = 0
var lastTappedAt: Date = Date()
func scheduleCheckResult() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
let timePassedSinceLastTap = Int(Date().timeIntervalSince(self.lastTappedAt))
print("last tap was \(timePassedSinceLastTap) ago")
// Wait a bit more for resolving final reaction. Adjust if you want quicker/slower taps (more than 1s for slower, less for quiceker)
guard timePassedSinceLastTap > 1 else {
return self.scheduleCheckResult()
}
print("FINISHED WITH: \(self.tapCount)")
// Verify result
switch self.tapCount {
case let n where n >= 10:
print("Super duper happy")
case let n where n >= 5:
print("Very happy")
default:
print("Medium happy")
}
// Reset state
self.tapCount = 0
}
}
@IBAction func didTap() {
if tapCount == 0 {
scheduleCheckResult()
}
lastTappedAt = Date()
tapCount += 1
}