当前位置:  开发笔记 > 前端 > 正文

设备锁定时NSTimer不起作用

如何解决《设备锁定时NSTimer不起作用》经验,为你挑选了1个好方法。

我有一个应用程序,我希望每次都在后台工作,只有当用户关闭(终止)它失败时(如每日警报).我的代码是:

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秒后关闭.如果设备锁定,计时器也会关闭.



1> Darshan Moth..:

要在后台运行代码,请参阅此链接: - https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

备注: -

    应用程序仅执行10分钟的后台执行 - 在此持续时间之后,计时器将停止触发.

    从设备锁定到iOS 7或更高版本时,它将几乎立即暂停前台应用程序.锁定iOS 7或更高版本的应用程序后,计时器不会触发.

推荐阅读
小白也坚强_177
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有