如何在 iOS 7 中超过 180 秒在后台运行 NSTimer?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22628922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:48:36  来源:igfitidea点击:

How to run NSTimer in background beyond 180sec in iOS 7?

iostimernstimer

提问by Deepak Gupta

I have tried this but not working more than 180 sec in iOS 7 and Xcode 4.6.2. Please help me

我已经尝试过这个,但在 iOS 7 和 Xcode 4.6.2 中工作时间不超过 180 秒。请帮我

    UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
        UIApplication *app = [UIApplication sharedApplication];
       bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
            [app endBackgroundTask:bgTask];
        }];
        NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:20 target:self   selector:@selector(timerMethod) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
     -(void) timerMethod{

     NSLog(@"in timerMethod");
    }

回答by Tarek Hallak

Unless you enable one of the Background modes, it is not gonna work.

除非您启用其中之一,否则Background modes它将无法正常工作。

Why?

为什么?

  • You have around 10 minutes of background execution after this the timer is stopped by ios.

  • The timer will not fire after app is locked (iOS7), since ios suspends the foreground app and bgTaskwill not get fire again.

  • 在此计时器被 ios 停止之后,您有大约 10 分钟的后台执行时间。

  • 应用程序被锁定(iOS7)后计时器不会触发,因为 ios 挂起前台应用程序并且bgTask不会再次触发。

There is some workarounds, consider to check below question:

有一些解决方法,请考虑检查以下问题:

iphone - NSTimers in background

iphone - 后台的 NSTimers

Scheduled NSTimer when app is in background?

当应用程序在后台时调度 NSTimer?

NSTimer on background IS working

后台的 NSTimer 正在工作