我有一個應用程序,我想每次都在後臺工作,並且只有當用戶關閉(終止)它失敗(如每日警報)時。我的代碼是:當設備鎖定時,NSTimer沒有工作
的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;
}
和視圖的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秒後關閉。並且如果設備是鎖定定時器也是關閉的。
由於iOS版7.1可以運行在後臺3分鐘,如果你想比最高可以使用'[UIApplicationsharedApplication] beginBackgroundTaskWithExpirationHandler:^ { }]運行10分鐘就可以' –
你可能想了解更多關於iOS背景執行效果如何__ [來自最佳](https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html)__ _(劇毒警報:蘋果)_。 – holex
我閱讀每一個文件,我知道這一切。但要超過3分鐘或10分鐘的應用程序(如鬧鐘) – Sina