从背景返回时隐藏音量HUD

时间:2018-05-16 05:21:08

标签: ios swift

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

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

我搜索并得到这些答案。

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

 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?

2 个答案:

答案 0 :(得分:0)

只需在您的应用代理中添加此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
    }

答案 1 :(得分:0)

尝试使用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)
}