即使 ViewController 在 iOS 中消失,仍继续执行方法

发布于 2024-12-28 07:51:59 字数 105 浏览 1 评论 0原文

我有一个视图可以使用导航控制器推送另一个视图。在第二个视图中,我播放一个音频,即使用户返回第一个视图,弹出第二个视图,我也想继续播放该音频,就像在 iPod 应用程序中一样。我怎样才能做到这一点?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情绪失控 2025-01-04 07:51:59

您应该从视图控制器中抽象音频播放,因为它并不是真正相关的功能(而且它可以让您做您想做的事情)。我建议创建一个单例对象,其功能是播放指定的歌曲,暂停/停止它,并从中检索状态(例如 isPlaying 等)。我不会深入探讨单例是什么/如何制作单例,因为其他堆栈溢出帖子和快速谷歌搜索都会产生结果,但是基本前提是您创建一个类并向其中添加此方法:

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

然后,您可以创建如下方法:

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

从任何 #import 单例对象的类中,您可以调用:

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

单例对象是只能实例化一次并在应用程序执行期间“持续存在”的对象,所以它会继续做你做的事情不管你的视图控制器发生了什么,都告诉它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文