NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to detect shake gestures

Paul Hudson    @twostraws   

Updated for Xcode 12.5

SwiftUI doesn’t have a built-in way to detect the user shaking their device, but it doesn’t take much work to create one yourself by overriding motionEnded() in UIWindow and creating a custom view modifier.

First, add an extension to UIDevice to track a new notification that will be sent when a shake gesture happens:

extension UIDevice {
    static let deviceDidShakeNotification = Notification.Name(rawValue: "deviceDidShakeNotification")
}

Second, create an extension on UIWindow to override the default motionEnded() method. This is where UIKit sends shake gestures, so we’re going to look for that happening and translate it into our new notification:

extension UIWindow {
     open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            NotificationCenter.default.post(name: UIDevice.deviceDidShakeNotification, object: nil)
        }
     }
}

Third, create a custom view modifier that we can use to watch for our new notification being posted, and call a function of our choosing when it happens:

struct DeviceShakeViewModifier: ViewModifier {
    let action: () -> Void

    func body(content: Content) -> some View {
        content
            .onAppear()
            .onReceive(NotificationCenter.default.publisher(for: UIDevice.deviceDidShakeNotification)) { _ in
                action()
            }
    }
}

Tip: At the time of writing view modifiers do not work with onReceive() unless you first add onAppear(), which is why it appears above. Yes, it’s empty, but it acts as a workaround for the problem.

Finally, create a View extension that wraps up your new modifier neatly, like this:

extension View {
    func onShake(perform action: @escaping () -> Void) -> some View {
        self.modifier(DeviceShakeViewModifier(action: action))
    }
}

Done! Now you can go ahead and add an onShake() modifier to any view you want, providing some custom code to run when the shake gesture happens.

For example, this shows a text view and prints a message when a shake gesture happens:

Text("Shake me!")
    .onShake {
        print("Device shaken!")
    }
Hacking with Swift is sponsored by Emerge

SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.

Set up a demo!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.