Swift
iPhone development
iOS programming
Vibration functionality
Swift tutorial

How to make iPhone vibrate using Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Making an iPhone vibrate in Swift looks easy, but there are several APIs with different behavior, capabilities, and OS requirements. Older code uses system vibration services from AudioToolbox. Modern apps often use UIFeedbackGenerator for lightweight haptics or CoreHaptics for custom patterns. The best API depends on your use case: simple alert feedback, button tap feedback, or a fully designed haptic sequence.

A robust implementation should also consider device capability, user settings, and context. For example, some haptic patterns are unavailable on older devices, and overly frequent vibration can hurt usability. Good haptics are brief, intentional, and tied to meaningful UI state changes.

Core Sections

1. Quick vibration with AudioToolbox

For a basic vibration trigger, this is still the smallest API surface:

swift
1import AudioToolbox
2
3func vibrateSimple() {
4    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
5}

This works for straightforward alert feedback, but it has limited customization and no nuanced intensity control.

2. Prefer UIFeedbackGenerator for UI interactions

For button taps, success states, or warnings, use UIKit feedback generators. They integrate better with iOS interaction patterns.

swift
1import UIKit
2
3func notifySuccess() {
4    let generator = UINotificationFeedbackGenerator()
5    generator.prepare()
6    generator.notificationOccurred(.success)
7}
8
9func impactLight() {
10    let generator = UIImpactFeedbackGenerator(style: .light)
11    generator.prepare()
12    generator.impactOccurred()
13}

Call prepare() shortly before the event to reduce latency. Do not create generators repeatedly in hot paths; reuse when appropriate.

3. Create custom haptic patterns with CoreHaptics

If you need richer tactile design, use CoreHaptics (iOS 13+). Always check capability first.

swift
1import CoreHaptics
2
3final class HapticManager {
4    private var engine: CHHapticEngine?
5
6    init?() {
7        guard CHHapticEngine.capabilitiesForHardware().supportsHaptics else {
8            return nil
9        }
10        do {
11            engine = try CHHapticEngine()
12            try engine?.start()
13        } catch {
14            return nil
15        }
16    }
17
18    func playTapPattern() {
19        let intensity = CHHapticEventParameter(parameterID: .hapticIntensity, value: 0.8)
20        let sharpness = CHHapticEventParameter(parameterID: .hapticSharpness, value: 0.6)
21        let event = CHHapticEvent(eventType: .hapticTransient,
22                                  parameters: [intensity, sharpness],
23                                  relativeTime: 0)
24        do {
25            let pattern = try CHHapticPattern(events: [event], parameters: [])
26            let player = try engine?.makePlayer(with: pattern)
27            try player?.start(atTime: 0)
28        } catch {
29            // handle gracefully
30        }
31    }
32}

This gives precise control over intensity and timing for brand-specific tactile behavior.

4. Integrate with app state intentionally

Trigger haptics on meaningful transitions: completed payment, failed form submission, drag snap, confirmation. Avoid vibrating on every minor state change. If feedback is coupled to async operations, trigger on final result, not on request start.

swift
1func saveProfile() async {
2    do {
3        try await api.saveProfile()
4        UINotificationFeedbackGenerator().notificationOccurred(.success)
5    } catch {
6        UINotificationFeedbackGenerator().notificationOccurred(.error)
7    }
8}

5. Test on real devices

Simulators do not reproduce physical haptic behavior reliably. Validate rhythm, perceived strength, and event timing on target hardware.

Common Pitfalls

  • Using only AudioToolbox for modern UI feedback where UIFeedbackGenerator gives better semantics.
  • Triggering haptics too frequently, causing noisy and fatiguing interactions.
  • Ignoring capability checks before using CoreHaptics, which breaks on unsupported devices.
  • Creating new feedback generator objects for every tap in tight loops, increasing latency.
  • Testing exclusively in simulator and shipping unvalidated tactile behavior.

Summary

In Swift, iPhone vibration can be implemented at three levels: simple system vibration (AudioToolbox), interaction-level haptics (UIFeedbackGenerator), or fully custom patterns (CoreHaptics). Choose the lightest API that matches your product need, gate advanced patterns by hardware capability, and trigger feedback only for meaningful events. With these practices, haptics become a useful part of UX rather than an afterthought.

A practical way to keep this issue from returning is to turn the fix into a lightweight runbook. Capture the exact environment assumptions (tool versions, runtime flags, cluster or platform settings, and required dependencies), then store a short verification command sequence that any teammate can run from a clean setup. This makes troubleshooting deterministic instead of person-dependent and reduces rework during on-call incidents.

It also helps to add one automated guardrail in CI or pre-deploy checks that validates the critical assumption described above. That guardrail might be a linter rule, a smoke test, a schema check, a policy validation step, or a minimal integration test. When the same class of failure is caught before release, teams spend less time on emergency debugging and more time on controlled improvements.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.