Swift System volume button hold at the background

417 views Asked by At

1st LINK works for a ViewController.

let volumeView = MPVolumeView(frame: CGRect.zero)
self.view.addSubview(volumeView)
NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)

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

2nd LINK is about background usage.

THE QUESTION: How to notify/apply action in the application if the volume button is pressed over 5 seconds at the background or when the screen is locked?

Note: In case of ViewController we can add the subview of MPVolumeView

According to my latest researches: UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum) could be used to check the button... however, it doesn't seem to work from AppDelegate.swift

Moreover, according to WWDC 2019 presentation there is a way through the BackgroundTasks.

All I did find about the background processes that you can run them before the application termination and wait until completion or use buttons check/events from the launched application. We can catch the button Event on Android through the accessibility service. Is there any similar way on iOS?

1

There are 1 answers

0
Harsh Lad On
import UIKit  
import MediaPlayer  
import AVFoundation  

class ViewController: UIViewController {  

    private var audioLevel : Float = 0.0  

    override func viewDidLoad() {  
        super.viewDidLoad()  
        // Do any additional setup after loading the view, typically from a nib.  
    }  

    override func viewWillAppear(_ animated: Bool) {  
        listenVolumeButton()  
    }  

    func listenVolumeButton(){  

        let audioSession = AVAudioSession.sharedInstance()  
        do {  
            try audioSession.setActive(true, options: [])  
            audioSession.addObserver(self, forKeyPath: "outputVolume",  
                                     options: NSKeyValueObservingOptions.new, context: nil)  
            audioLevel = audioSession.outputVolume  
        } catch {  
            print("Error")  
        }  
    }  

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {  
        if keyPath == "outputVolume"{  
            let audioSession = AVAudioSession.sharedInstance()  
            if audioSession.outputVolume > audioLevel {  
                print("Hello")  
                audioLevel = audioSession.outputVolume  
            }  
            if audioSession.outputVolume < audioLevel {  
                print("GoodBye")  
                audioLevel = audioSession.outputVolume  
            }  
            if audioSession.outputVolume > 0.999 {  
                (MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(0.9375, animated: false)  
                audioLevel = 0.9375  
            }  

            if audioSession.outputVolume < 0.001 {  
                (MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(0.0625, animated: false)  
                audioLevel = 0.0625  
            }  
        }  
    }  


}