0

我想让我的 iOS 应用程序每 5 分钟执行一次特定功能。怎么做?一个函数很简单,比如

batter = 95; // will be calculated.. every time is differ
[UIApplication sharedApplication].applicationIconBadgeNumber = batter;

我需要在后台为它制作计时器

4

2 回答 2

5

除非您的应用属于以下类别之一,否则您无法在后台执行此操作:VOIP、音频播放或位置更新。如果您放置计时器,当应用程序进入后台时,它们将变为无效。

于 2013-02-12T14:53:46.103 回答
0

在我的.h 文件中有一个像这样声明的计时器:

NSTimer *MyTimer;
@property (nonatomic, retain) NSTimer *MyTimer;

然后在.m 文件上,我这样声明:

UIBackgroundTaskIdentifier BackGroundTask;
UIApplication  *app = [UIApplication sharedApplication];
BackGroundTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:BackGroundTask]; 
}];
self.MyTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self
selector:@selector(TimerMethod) userInfo:nil repeats:YES];

以下是每 5 秒调用一次的计时器方法:

 -(void)TimerMethod 
   {
        batter = 95; // will be calculated.. every time is differ
    [UIApplication sharedApplication].applicationIconBadgeNumber = batter;

    }
于 2013-02-12T14:56:54.567 回答