Skip to content

Instantly share code, notes, and snippets.

@JJTech0130
Created June 30, 2022 23:38
Show Gist options
  • Save JJTech0130/388f5fbe5b3cee15fc42b49a22b9cab2 to your computer and use it in GitHub Desktop.
Save JJTech0130/388f5fbe5b3cee15fc42b49a22b9cab2 to your computer and use it in GitHub Desktop.
Extension for UIApplication that allows capturing Volume Button events in Swift
//
// UIApplication+VolumeButtons.swift
//
// Based on https://stackoverflow.com/a/70815088
//
import UIKit
// Stub protocol to allow us to call private methods
@objc private protocol UIApplicationPrivate {
@objc func setWantsVolumeButtonEvents(_:Bool)
}
extension UIApplication {
/**
Capture volume button events.
Enabling this setting will temporarily disable system-default volume button functionality,
and sends the relavent notifications to the `default` notification center.
- Parameter enabled: Enable or disable capturing of volume button events
*/
public func setWantsVolumeButtonEvents(_ enabled: Bool) {
let application = unsafeBitCast(self, to: UIApplicationPrivate.self)
application.setWantsVolumeButtonEvents(enabled)
}
}
extension UIApplication {
/// Volume up button was pressed.
public static let volumeUpButtonDownNotification: NSNotification.Name = NSNotification.Name("_UIApplicationVolumeUpButtonDownNotification")
/// Volume up button was released.
public static let volumeUpButtonUpNotification: NSNotification.Name = NSNotification.Name("_UIApplicationVolumeUpButtonUpNotification")
/// Volume down button was pressed.
public static let volumeDownButtonDownNotification: NSNotification.Name = NSNotification.Name("_UIApplicationVolumeDownButtonDownNotification")
/// Volume down button was released.
public static let volumeDownButtonUpNotification: NSNotification.Name = NSNotification.Name("_UIApplicationVolumeDownButtonUpNotification")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment