Creating a haptic feedback pattern in swift 3

1.5k views Asked by At

I am very new to Swift and programming. I'm trying to create a pattern of haptic feedback triggered by a UILongPressGestureRecognizer. When the user "long presses" the screen, I want the phone to vibrate three times with a 1 second delay between each vibration. I tried using "sleep" to accomplish the 1 second delays, but this didn't work. What is the best way to do this correctly?

var feedbackGenerator : UIImpactFeedbackGenerator? = nil

func performFeedbackPattern() {

    //create the feedback generator
    feedbackGenerator = UIImpactFeedbackGenerator(style: .heavy)
    feedbackGenerator?.prepare()

    //play the feedback three times with 1 second between each feedback
    feedbackGenerator?.impactOccurred()
    sleep (1)
    feedbackGenerator?.impactOccurred()
    sleep (1)
    feedbackGenerator?.impactOccurred()
}


@IBAction func gestureRecognizer(_ sender: UILongPressGestureRecognizer) {
    switch sender.state {
        case .began:
            performFeedbackPattern()
        default: break
    }
2

There are 2 answers

0
Sapozhnik Ivan On

Recently I was doing something similar and come up with a small pod you can take a look. Here is the link https://github.com/iSapozhnik/Haptico

So the idea is to build an OperationQueue with the banch of Operations. One operation could be your haptic feedback and another one - pause operation.

0
efremidze On

You can create an OperationQueue and add operations with haptic feedback. The operation would look like this:

class HapticFeedbackOperation: Operation {
    override func main() {
        // Play the haptic feedback
        UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
    }
}

You might want to add a delay between the operations.

Checkout my open source framework Haptica, it supports both Haptic Feedback, AudioServices and unique vibrations patterns. Works on Swift 4.2, Xcode 10