IPhone notification volume button

I'm trying to get a notification when the volume button is pressed (i.e. on the left side of the phone). I googled a lot and it seems to me that I should use mediaPlayer, but since I am new to iOS, and Swift cannot make it work. That's what I'm doing:

import UIKit
import MediaPlayer
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var mediaPlayer: MPMusicPlayerController = MPMusicPlayerController()

        NSNotificationCenter.defaultCenter().addObserver(mediaPlayer,
            selector: "volumeIsChanged:",
            name: MPMusicPlayerControllerVolumeDidChangeNotification,
            object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func volumeIsChanged(notification: NSNotification){
        println("Volume Is Changed")
    }
}

PS: I know that changing the behavior of the iPhone hardware is undesirable for Apple.

+4
source share
2 answers

try the following:

func hookVolume() {
    var volumeView = MPVolumeView(frame: CGRectMake(-500, -500, 0, 0)) 
    self.window?.addSubview(volumeView)

    NSNotificationCenter.defaultCenter().addObserver(self,
        selector: "volumeChanged:",
        name: "AVSystemController_SystemVolumeDidChangeNotification",
        object: nil)

}

func volumeChanged(notification: NSNotification) {
    let volume = notification.userInfo!["AVSystemController_AudioVolumeNotificationParameter"] as! Float        
}

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    hookVolume()
}
+1
source

For Swift 4, the updated code should look like this. Also do not forget to remove the observer - always

override func viewDidLoad() {
    super.viewDidLoad()

    // slider to visualize the volume change
    var volumeView = UISlider(frame: CGRect(x:0,y:0,width:300,height:50))
    volumeView.tag = 100
    self.view.addSubview(volumeView)

    //Add observer for the volume change event
    NotificationCenter.default.addObserver(self, selector: #selector(NowPlayingViewController.volumeChanged(_:)), name: NSNotification.Name("AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
}

@objc func volumeChanged(notification: NSNotification) {
    let volume = notification.userInfo!["AVSystemController_AudioVolumeNotificationParameter"] as! Float
    print("Volume value:\(volume)")

    //Get the slider by its tag
    let volumeView = self.view.viewWithTag(100) as! UISlider
    //Update the slider value to correspond to the volume
    volumeView.value = volume
}

deinit {
    // Don't forget to remove the observer
    NotificationCenter.default.removeObserver(self,
                                              name: Notification.Name("AVSystemController_SystemVolumeDidChangeNotification"),
                                              object: nil)
}
0
source

All Articles