Vernissage/ServicesKit/Sources/ServicesKit/HapticService.swift

62 lines
1.9 KiB
Swift
Raw Normal View History

2023-01-06 13:05:21 +01:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
2023-03-28 10:35:38 +02:00
// Licensed under the Apache License 2.0.
2023-01-06 13:05:21 +01:00
//
2023-02-19 12:49:44 +01:00
import CoreHaptics
import UIKit
2023-04-07 16:59:18 +02:00
import EnvironmentKit
2023-01-06 13:05:21 +01:00
2023-02-19 12:49:44 +01:00
public class HapticService {
public static let shared: HapticService = .init()
2023-01-06 13:05:21 +01:00
2023-02-19 12:49:44 +01:00
public enum HapticType {
case buttonPress
case dataRefresh(intensity: CGFloat)
case notification(_ type: UINotificationFeedbackGenerator.FeedbackType)
case tabSelection
2023-02-20 10:57:16 +01:00
case animation
2023-01-06 13:05:21 +01:00
}
2023-02-19 12:49:44 +01:00
private let selectionGenerator = UISelectionFeedbackGenerator()
private let impactGenerator = UIImpactFeedbackGenerator(style: .heavy)
private let notificationGenerator = UINotificationFeedbackGenerator()
2023-01-06 13:05:21 +01:00
2023-02-19 12:49:44 +01:00
private init() {
selectionGenerator.prepare()
impactGenerator.prepare()
2023-01-06 13:05:21 +01:00
}
2023-02-19 12:49:44 +01:00
public func fireHaptic(of type: HapticType) {
guard supportsHaptics else { return }
switch type {
case .buttonPress:
2023-03-05 09:53:06 +01:00
if ApplicationState.shared.hapticButtonPressEnabled {
impactGenerator.impactOccurred()
}
2023-02-19 12:49:44 +01:00
case let .dataRefresh(intensity):
2023-03-05 09:53:06 +01:00
if ApplicationState.shared.hapticRefreshEnabled {
impactGenerator.impactOccurred(intensity: intensity)
}
2023-02-19 12:49:44 +01:00
case let .notification(type):
2023-03-05 09:53:06 +01:00
if ApplicationState.shared.hapticNotificationEnabled {
notificationGenerator.notificationOccurred(type)
}
2023-02-19 12:49:44 +01:00
case .tabSelection:
2023-03-05 09:53:06 +01:00
if ApplicationState.shared.hapticTabSelectionEnabled {
selectionGenerator.selectionChanged()
}
2023-02-20 10:57:16 +01:00
case .animation:
2023-03-05 09:53:06 +01:00
if ApplicationState.shared.hapticAnimationEnabled {
selectionGenerator.selectionChanged()
}
2023-01-06 13:05:21 +01:00
}
}
2023-02-19 12:49:44 +01:00
public var supportsHaptics: Bool {
CHHapticEngine.capabilitiesForHardware().supportsHaptics
2023-01-06 13:05:21 +01:00
}
}