1

[description] I found answer how to hide volume HUD in StackOverflow and try it. Then it works at start up, but it doesn't work at returning from background.


I hope detect volume button press, and execute a certain process. Therefore, I would like to hide volume HUD.

I search it and get these answers.

I tried it in my code. (I use the system volume change to detect volume button press)

 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
    }
  }

It works when the application starts. However, it does not work when returning from the background (return from sleep or home).

What should I do to hide volume HUD at returning from background?

Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
kouchou
  • 11
  • 2

2 Answers2

1

Just in your app delegate add this self.window?.insertSubview(MPVolumeView(), at: 0)

Don't forget to add this 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
    }
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35
0

Try hiding the volume HUD in AppDelegate method :

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)
}
Amit
  • 4,837
  • 5
  • 31
  • 46