Home > AI > IOS > UIKit >

UINotificationFeedbackGenerator

A concrete UIFeedbackGenerator subclass that creates haptics to communicate successes, failures, and warnings.

Use notification feedback to communicate that a task or action has succeeded, failed, or produced a warning of some kind.

Step 1: Check if the device supports haptic feedback

print(UIDevice.current.value(forKey: "_feedbackSupportLevel"))


// 0 = Taptic not available
// 1 = First generation (tested on an iPhone 6s) ... which does NOT support UINotificationFeedbackGenerator, etc.
// 2 = Second generation (tested on an iPhone 7) ... which does support it.

Step 2: open system

Settings / Sound & Haptics / System Haptics

Step 3: Code

struct ContentView: View {
    let generator = UINotificationFeedbackGenerator()
    
    var body: some View {
        VStack(alignment: .center, spacing: 30.0) {
            Button(action: {
                self.generator.notificationOccurred(.success)
            }) {
                Text("Notification - Success")
            }
            
            Button(action: {
                self.generator.notificationOccurred(.error)
            }) {
                Text("Notification - Error")
            }
            
            Button(action: {
                self.generator.notificationOccurred(.warning)
            }) {
                Text("Notification - Warning")
            }
            
            Button(action: {
                let impactLight = UIImpactFeedbackGenerator(style: .light)
                impactLight.impactOccurred()
            }) {
                Text("Impact - Light")
            }
            
            Button(action: {
                let impactMed = UIImpactFeedbackGenerator(style: .medium)
                impactMed.impactOccurred()
            }) {
                Text("Impact - Medium")
            }
            
            Button(action: {
                let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
                impactHeavy.impactOccurred()
            }) {
                Text("Impact - Heavy")
            }
            
            Button(action: {
                let selectionFeedback = UISelectionFeedbackGenerator()
                selectionFeedback.selectionChanged()
            }) {
                Text("Selection Feedback - Changed")
            }
        }
        .padding(.all, 30.0)
    }
}

Leave a Reply