Liam Shalon
Liam Shalon

Reputation: 442

Calling ViewController's Method from App Delegate

Within my ViewController, Inbox, I'd like to call the method playAudio() from my App Delegate.

This is the method.

func playAudio(){

        let nowPlaying = MPNowPlayingInfoCenter.defaultCenter()

        let albumArtWork = MPMediaItemArtwork(image: UIImage(named: "testImage.jpg")!)

        nowPlaying.nowPlayingInfo = [MPMediaItemPropertyTitle:"Sonnnngggg",
            MPMediaItemPropertyArtist:"Arrrtttiiiissstttt",
            MPMediaItemPropertyArtwork:albumArtWork]
        audioPlayer.play()

    }

And I'd like to call it from my App Delegate...

if event!.subtype == UIEventSubtype.RemoteControlPlay {
                print("received remote play")
                //audioPlayer.play()
                Inbox.playAudio()
            }

The one problem is that because I have a audioPlayer and everything within my Inbox ViewController, and that it's probably already playing audio, it doesn't make sense to make an instance of Inbox to call playAudio(). So, please let me know if there are any workarounds in Swift.

Thanks, Liam

Upvotes: 0

Views: 1485

Answers (3)

alephao
alephao

Reputation: 1273

You can instantiate the AppDelegate and call the function you want

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.someFunction()

But it not seems to be a good pratice...

NSNotificationCenter:

Use this code in the place you want to call the function:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "anotherFunction", name: "SomeNotification", object: nil)

change anotherFunction to the function name you want to call.

On AppDelegate:

NSNotificationCenter.defaultCenter().postNotificationName("SomeNotification", object: nil)

Upvotes: 0

beyowulf
beyowulf

Reputation: 15331

In AppDelegate change to:

if event!.subtype == UIEventSubtype.RemoteControlPlay {
            print("received remote play")
            //audioPlayer.play()
            NSNotificationCenter.defaultCenter().postNotificationName("RemotePlayPressed", object: self)
        }

Then in Inbox view controller's viewDidLoad add:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "playAudio", name: "RemotePlayPressed", object: nil)

also add:

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

to Inbox view controller.

Upvotes: 1

André Slotta
André Slotta

Reputation: 14030

in your viewcontroller you reach your appdelegate via

(UIApplication.sharedApplication().delegate as! AppDelegate).playAudio()

Upvotes: 0

Related Questions