从后台返回时隐藏音量HUD



[描述] 我找到了如何在StackOverflow中隐藏音量HUD并尝试的答案。然后它在启动时工作,但在从后台返回时不起作用。


我希望检测音量按钮按下,并执行某个过程。 因此,我想隐藏音量HUD。

我搜索它并得到这些答案。

  • 隐藏设备音量HUD视图,同时使用MPVolumeView滑块辅助音量
  • 应用程序音乐播放器音量通知

我在我的代码中尝试过。(我使用系统音量变化来检测音量按钮按下)

private let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
private var systemVolumeSlider: UISlider? = nil
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let volumeView: MPVolumeView = MPVolumeView(frame: CGRect.zero)
if let volumeSlider: UISlider = volumeView.subviews.first as? UISlider {
self.systemVolumeSlider = volumeSlider
}
self.view.addSubview(volumeView)
do {
try self.audioSession.setActive(true)
} catch {
print("error: can not setActive")
}
self.audioSession.addObserver(
self, forKeyPath: "outputVolume", options: [.old, .new], context: nil
)
}
override func observeValue(
forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?
) {
// Process
}
}

它在应用程序启动时工作。但是,从后台返回(从睡眠或家中返回)时它不起作用。

从后台返回时应该怎么做才能隐藏音量 HUD?

只需在您的应用程序委托中添加此self.window?.insertSubview(MPVolumeView(), at: 0)

不要忘记添加此import MediaPlayer

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window?.insertSubview(MPVolumeView(), at: 0)
return true
}

尝试在AppDelegate方法中隐藏音量HUD:

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
self.window?.insertSubview(MPVolumeView(), at: 0)
}

最新更新