ios怎么让程序在后台运行代码

2025-05-04 20:11:25
推荐回答(1个)
回答1:

最好是具体到某个问题,这边我举两个例子:
1、比如我手上现在这个项目,首页动画是一直执行的,然而到后台在切回来就发现,动画不会动了,证明当程序到后台时,动画被强制干掉了,这边我用了kvc去监听这个动画,当一发现进程被干掉,会继续执行此动画,关键代码如下
//创建监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
//开启一个自转的动画
[_starMenuView.starView2.layer addAnimation:[self animationZ] forKey:@"transformRotationZ"];

2.后台执行定位
//这个是开启后台定位
Project setting -> Target -> Capabilities -> Background modes -> check Location updates.
//当然也不能少这两个属性在plist设置为yes
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription