gpt4 book ai didi

ios - 设备锁定时 NSTimer 不工作

转载 作者:行者123 更新时间:2023-12-01 17:56:17 25 4
gpt4 key购买 nike

我有一个应用程序,我希望每次都在后台工作,并且只有当用户关闭(终止)时它才会失败(例如每日闹钟)。我的代码是:

应用程序委托(delegate):

 - (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 Controller :

@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

注释:-

  1. 应用程序仅获得 10 分钟的后台执行时间 - 在此持续时间之后,计时器将停止触发。
  2. 从 iOS 7 或更高版本开始,当设备锁定时几乎会立即暂停前台应用程序。 iOS 7 或更高版本的应用程序锁定后,计时器将不会触发。

关于ios - 设备锁定时 NSTimer 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34181310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com