This library is compatible with the iOS, watchOS, and macOS platforms. On iOS/watchOS the haptics engine is used to play various haptic events. However, on macOS all events are simply skipped. MacOS support is provided simply to allow the same piece of SwiftUI code to interact with the haptics service, without having to “gate” its logic using an OS check.
Mocking of the service can be useful in previews as well as other applications. The HapticsService is shipped with mocking support that can be used in debug builds as follows:
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
PreviewView()
}
}
struct PreviewView : View {
@StateObject private var mockHapticsService = MockHapticsService()
@State private var eventsPlayed: Int = 0
var body: some View {
VStack {
Text("# of events played: \(eventsPlayed)")
ContentView()
.environmentObject(mockHapticsService as HapticsService)
}
.onAppear {
mockHapticsService.playCallback = { _ in
eventsPlayed += 1
}
}
}
}
#endif
SwiftUIHaptics Library
An open source library that provides a common service to use in projects that require haptics feedback.
Developed as re-usable components for various projects at XII’s iOS, macOS, and watchOS applications.
Installation
Swift Package Manager
SwiftUIHaptics
library to add to your projectDependencies
License
See the LICENSE file.
Supported Platforms
This library is compatible with the iOS, watchOS, and macOS platforms. On iOS/watchOS the haptics engine is used to play various haptic events. However, on macOS all events are simply skipped. MacOS support is provided simply to allow the same piece of SwiftUI code to interact with the haptics service, without having to “gate” its logic using an OS check.
Defining haptic events (Source)
A struct containing a series of
CHHapticEvent
s to be played via theHapticsService
.Creating haptic events (Source)
Single events
Creates a single
HapticEvent
, with the ability to specify all the parameters and defaulting others.Patterns
Creates a pattern of haptic events by combining all underlying events for the provided
HapticEvent
instances.From an existing
HapticEvent
Returns a time shifted
HapticEvent
with the provided relative time and play duration specified.HapticsService
(Source)Usage Example
Define your events
Wire up the
HapticsService
Fire events in your
View
sSupporting mocking
Mocking of the service can be useful in previews as well as other applications. The
HapticsService
is shipped with mocking support that can be used in debug builds as follows: