0

I'm trying to use NotificationCenter to send slider values (audio volume) to another view controller which contains the all the audio engine that I need. From the sender VC I tried this:

@IBAction func vol1ChangedFromMixer(sender: UISlider) {
    NotificationCenter.default.post(name: Notification.Name(rawValue: "vol1FromMixer"), object: nil)
    }

And then at receiver VC, in viewDidLoad:

//vol from mixer
    NotificationCenter.default.addObserver(self, selector: #selector(vol1FromMixer(_:)), name: Notification.Name(rawValue: "vol1FromMixer"), object: nil)

And later at the same receiver VC:

//vol from mixer function
      @objc func vol1FromMixer() {
        _engine.setAmpGain(Double(sender.value)*2.0, ofTrack: sender.tag)
}

Got error use of unresolved identifier "sender" at the receiver VC. For sure I'm not ready with the UISlider kind of values that can be sent. Any suggestion?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Sktsalad
  • 23
  • 4

2 Answers2

0

You need to pass sender from vol1ChangedFromMixer method. You can use this method, and pass sender in userInfo. Then retrieve it in vol1FromMixer

Sometheing like

@IBAction func vol1ChangedFromMixer(sender: UISlider) {
    NotificationCenter.default.post(name: Notification.Name(rawValue: "vol1FromMixer"), object: nil, userInfo: ["slider": sender])
}

@objc func vol1FromMixer(_ notification: Notification) {
    guard let sender = notification.userInfo["slider"] as? UISlider
         else { return }
    _engine.setAmpGain(Double(sender.value)*2.0, ofTrack: sender.tag)
}
Tien Nguyen
  • 599
  • 4
  • 13
0

A solution without Notification

1. create class 'DataManager'

this class is in my `Tools.swift` file
class DataManager {
    ///to call function in VCA from VCB
    ///needs three elements:
    /// 1. this class
    /// 2. 'DataManager.shared.fistVCYouNameIt1 = self’ in VCA in viewDidLoad()
    /// 3. 'DataManager.shared.fistVCYouNameIt1.myFuncInVcAToCallFromVcB()' in VCB (execute function in VCA)
    static let shared = DataManager()
    var fistVCYouNameIt1 = ViewController1() //class Name
    var fistVCYouNameIt2 = ViewController1() //class Name
    //var fistVCYouNameIt3 ...
}//end class DataManager

2. in you VCA in viewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()
    DataManager.shared.fistVCYouNameIt1 = self //to call func ‘myFuncInVcAToCallFromVcB ()’ from VCB in VCA. Without this e.g. your outlets are not accessible within VCA, when called from VCB

    //other code
}

3. in your VCB

The point in your code VCB to call function in VCA:
...
DataManager.shared.fistVCYouNameIt.myFuncInVcAToCallFromVcB() //execute func in VCA 
...

4. in your VCA:

func myFuncInVcAToCallFromVcB (){
    //your code here
}
RvdH
  • 72
  • 6