gabriel_vincent
gabriel_vincent

Reputation: 1250

Continue to perform method even when it's ViewController disappear in iOS

I have a view that pushes another view with navigation controller. In this second view I play an audio which I want to continue playing even when the user gets back to the first view, popping the second view away, just like in iPod app. How can I do that?

Upvotes: 1

Views: 123

Answers (1)

Jack Lawrence
Jack Lawrence

Reputation: 10772

You should abstract your audio playing from your view controller, since it's not really related functionality (and plus it'll let you do what you want). I would suggest creating a singleton object who's functionality is to play a specified song, pause/stop it, and retrieve statuses from it (such as isPlaying, etc). I'm not going to go deeply into what a singleton is/how to make one, since other stack overflow posts and a quick google search will yield results, however the basic premise is that you create a class and add this method to it:

+ (id)sharedInstance
{
    static dispatch_once_t dispatchOncePredicate = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&dispatchOncePredicate, ^{
        _sharedObject = [[self alloc] init];
    });
    return _sharedObject;
}

Then you can create a method like so:

+ (void)playSongWithFile:(NSString *)fileName
{
    // retrieve the file and play it
}

And from any class in which you #import your singleton object, you can call:

[[MySingleton sharedInstance] playSongWithFile:@"awesomesong.mp3"];

A singleton object is an object that can only be instantiated once and "lives on" for the duration of your app's execution, so it'll continue doing what you tell it regardless of what's going on with your view controllers.

Upvotes: 1

Related Questions