從 iPhone 最初的普通長震模式井濒,到 6s 時代的 Peek、Pop,以及現(xiàn)在的 iPhone 7 獨(dú)有的特殊震動反饋肆汹,都進(jìn)行了簡單的封裝。
Github: https://github.com/Zane6w/Feedback
import UIKit
import AVFoundation
import AudioToolbox
fileprivate var audioPlayer: AVAudioPlayer?
/// 震動反饋示例音樂
fileprivate func playSound(forResource: String) {
let bundle = Bundle(identifier: "com.zhi.HapticFeedbackKit")
let path = bundle?.path(forResource: "FeedbackSounds", ofType: "bundle")
let fileBundle = Bundle(path: path!)
let url = fileBundle?.url(forResource: forResource, withExtension: "mp4")
audioPlayer = try? AVAudioPlayer(contentsOf: url!)
audioPlayer?.play()
}
/// 觸覺反饋 (適用于 iPhone 7予权、7 Plus 及其以上機(jī)型)
open class HapticFeedback {
@available(iOS 10.0, *)
public struct Notification {
fileprivate static var generator: UINotificationFeedbackGenerator = {
let generator = UINotificationFeedbackGenerator()
generator.prepare()
return generator
}()
public static func function() {
print(generator)
}
public static func successSound() {
playSound(forResource: "success")
}
public static func warningSound() {
playSound(forResource: "warning")
}
public static func errorSound() {
playSound(forResource: "error")
}
public static func success() {
occurred(.success)
}
public static func warning() {
occurred(.warning)
}
public static func error() {
occurred(.error)
}
fileprivate static func occurred(_ notificationType: UINotificationFeedbackType) {
generator.notificationOccurred(notificationType)
generator.prepare()
}
}
@available(iOS 10.0, *)
public struct Impact {
fileprivate static var generator: UIImpactFeedbackGenerator?
public static func lightSound() {
playSound(forResource: "impact_light")
}
public static func mediumSound() {
playSound(forResource: "impact_medium")
}
public static func heavySound() {
playSound(forResource: "impact_heavy")
}
public static func light() {
impactOccurred(.light)
}
public static func medium() {
impactOccurred(.medium)
}
public static func heavy() {
impactOccurred(.heavy)
}
fileprivate static func impactOccurred(_ style: UIImpactFeedbackStyle) {
generator = UIImpactFeedbackGenerator(style: style)
generator?.prepare()
generator?.impactOccurred()
}
}
@available(iOS 10.0, *)
public struct Selection {
fileprivate static var generator: UISelectionFeedbackGenerator = {
let generator = UISelectionFeedbackGenerator()
generator.prepare()
return generator
}()
public static func selectionSound() {
playSound(forResource: "selection")
}
public static func selection() {
generator.selectionChanged()
generator.prepare()
}
}
@available(iOS 9.0, *)
open class func peek() {
AudioServicesPlaySystemSound(1519)
}
@available(iOS 9.0, *)
open class func pop() {
AudioServicesPlaySystemSound(1520)
}
@available(iOS 9.0, *)
open class func error() {
AudioServicesPlaySystemSound(1521)
}
open class func vibration() {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
}