Implementing UIFeedbackGenerator on Swift 4, Xcode 9 & iOS 11


(Karthik Kamalakannan) #1

I’ve been playing around with Xcode 9, Swift 4 for our super secret project. I wanted to implement a haptic feedback when the user performs a particular action on the app. Here’s a gist of everything that you need to do to get this done.

There are three subclasses for UIFeedbackGenerator:

  1. UISelectionFeedbackGenerator
  2. UIImpactFeedbackGenerator
  3. UINotificationFeedbackGenerator

Selection:

  • Used when a user needs feedback from the phone for actions like scrolling and selections.
  • Best used when moving from one ViewController to another or when using a Segue

Here’s the code to get this done:

let selectionFeedbackGenerator = UISelectionFeedbackGenerator()
selectionFeedbackGenerator.selectionChanged()

Notification

  • Most commonly used
  • Use it when you want to notify the user about some error or success message or a warning

Here’s the code to send a success notification via Haptic feedback:

let successNotificationFeedbackGenerator = UINotificationFeedbackGenerator()
successNotificationFeedbackGenerator.notificationOccurred(.success)

Here’s the code to send a warning notification via Haptic feedback:

let warningNotificationFeedbackGenerator = UINotificationFeedbackGenerator()
warningNotificationFeedbackGenerator.notificationOccurred(.warning)

Here’s the code to send a error notification via Haptic feedback:

let errorNotificationFeedbackGenerator = UINotificationFeedbackGenerator()
errorNotificationFeedbackGenerator.notificationOccurred(.error)

Impact feedbacks

  • Majorly used when trying to notify the user during impact situations (most likely in a game)
  • Impact has three typed of feedbacks:
  1. Light
  2. Medium
  3. Heavy

Here’s how to go about Light Impact Haptic feedback on iOS:

let lightImpactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light)
lightImpactFeedbackGenerator.impactOccurred()

Here’s how to go about Medium Impact Haptic feedback on iOS:

let lightImpactFeedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
lightImpactFeedbackGenerator.impactOccurred()

Here’s how to go about Heavy Impact Haptic feedback on iOS:

let lightImpactFeedbackGenerator = UIImpactFeedbackGenerator(style: .heavy)
lightImpactFeedbackGenerator.impactOccurred()