我有一个应用程序,我希望每次都在后台工作,只有当用户关闭(终止)它失败时(如每日警报).我的代码是:
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; }
和查看控制器:
@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秒后关闭.如果设备锁定,计时器也会关闭.
要在后台运行代码,请参阅此链接: - https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
备注: -
应用程序仅执行10分钟的后台执行 - 在此持续时间之后,计时器将停止触发.
从设备锁定到iOS 7或更高版本时,它将几乎立即暂停前台应用程序.锁定iOS 7或更高版本的应用程序后,计时器不会触发.