iosmedia-playeraudiokitmpvolumeview

(Expected Declaration) error when using MPVolumeView


Im trying to setup MPVolumeView. Even though I declare the view, when putting "volumeView.addSubview(volView)" it gives me the error the error "expected declaration". I don't what I am doing wrong?

import UIKit
import AudioKitUI
import AudioKit
import MediaPlayer

class SDViewController: UIViewController {
    @IBOutlet var volumeView: UIView!

let volView = MPVolumeView()
    volumeView.addSubview(volView)
    UIApplication.shared.keyWindow?.insertSubview(volView, at: 0)
    volView.frame.origin.x = -1000

}

Solution

  • The class SDViewController hasn't been instantiated yet and therefore neither has volumeView.

    You'll need to put that code inside a class method and call it from viewDidLoad() or something like that.

    import UIKit import MediaPlayer

    class SDViewController: UIViewController {
    
        @IBOutlet var volumeView: UIView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            volumeView.addSubview(volView)
            UIApplication.shared.keyWindow?.insertSubview(volView, at: 0)
            volView.frame.origin.x = -1000
        }
    
    }