我有一个应用程序,我希望每次都在后台工作,只有当用户关闭(终止)它失败时(如每日警报)。我的代码是:
的AppDelegate:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
backgroundUpdateTask = 0;
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application{
}
- (void)applicationDidEnterBackground:(UIApplication *)application{
backgroundUpdateTask = [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
if (application.applicationIconBadgeNumber > 0) {
application.applicationIconBadgeNumber = 0;
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
[self endBackgroundUpdateTask];
if (application.applicationIconBadgeNumber > 0) {
application.applicationIconBadgeNumber = 0;
}
}
- (void)applicationDidBecomeActive:(UIApplication *)application{
lte = [[NSUserDefaults standardUserDefaults] valueForKey:@"LTE"];
if (lte == nil) {
[Utility GetNewNotification:lte];
lte = [[[notifyDic objectForKey: @"Notification"]valueForKey:@"LTE"]valueForKey:@"text"];
[[NSUserDefaults standardUserDefaults] setValue:lte forKey:@"LTE"];
}
}
- (void)applicationWillTerminate:(UIApplication *)application{
}
- (void)endBackgroundUpdateTask{
[[UIApplication sharedApplication]endBackgroundTask:backgroundUpdateTask];
backgroundUpdateTask = UIBackgroundTaskInvalid;
}
和View Controler:
@implementation ViewController
{
NSTimer *myTimer;
int counter;
}
-(void)CheckTimer{
if(counter == 0){
counter = 60;
NSString* lte = [[NSUserDefaults standardUserDefaults] valueForKey:@"LTE"];
[Utility GetNewNotification:lte];
}
else {
counter --;
//do your video playing work here
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
/// Counter for get new notification
counter = 60;
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(CheckTimer) userInfo:nil repeats:YES];
}
我希望每60秒计时器触发一次,服务就是呼叫。但是在应用程序转到后台计时器180秒后关闭。如果设备锁定,计时器也会关闭。
答案 0 :(得分:6)
要在后台运行代码,请参阅以下链接: https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
注意: -
答案 1 :(得分:0)
@Darshan Mothreja对他的回答是正确的。如果您想在后台运行代码,那么实际执行操作的时间有限。在那段时间过后,你的运气不好,直到你的应用程序回到前台。
根据您要完成的任务,您可能希望查看AppDelegate中的生命周期方法。
您可能想要查看该方法:
- (void)applicationDidBecomeActive:(UIApplication *)application;
并为其添加更多更新代码。这将允许您在应用程序返回到前台时更新内容或获取新数据。