【问题标题】:Hide volume HUD when returning from background从后台返回时隐藏音量 HUD
【发布时间】:2018-05-16 05:21:08
【问题描述】:

[description] 我找到了如何在 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?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-30
        • 2014-08-18
        • 2018-08-18
        • 1970-01-01
        • 2018-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多