从背景中消防NSTimer

时间:2014-03-18 11:08:08

标签: ios iphone background nstimer

我知道这里有一些问题,但我的问题与他们有点不同,这就是我提出这个问题的原因。目前我有一个NSTimer,每2分钟就会开火一次。当计时器被触发时,我的方法有25%的可能性被调用(这是一个游戏)。例如,我的NSTimer触发,现在从0-3生成随机数。如果此随机数等于0,则应调用我的方法。当我的应用程序进入后台模式时,我想要完全相同的行为。当NSTimer被触发时,应生成随机数,如果此数字等于0,则应发布UILocalNotification。

我的代码目前看起来像这样:

    - (IBAction)toggleBattleMode:(id)sender
{
    if (self.battleMode == NO)
    {
        self.battleMode = YES;
        battleTimer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(pushBattle:) userInfo:nil repeats:YES];
        [self performSelector:@selector(fireTimer:) withObject:self afterDelay:10];
        [sender setEnabled:YES];
        [sender setAlpha:1.0];
    }
    else
    {
        [battleTimer invalidate];
        battleTimer = nil;
        [sender setEnabled:NO];
        [sender setAlpha:0.5];
    }
}


- (void)fireTimer:(id)sender
{
    [battleTimer fire];
}


- (IBAction)pushBattle:(id)sender
{
    int randNum = rand() % (4);
    if(randNum == 0) {
    NSArray *boundingBox = [dataHelper getBoundingBox:map.userLocation.coordinate];
    NSArray *phrases = [[NSArray alloc]initWithObjects:@"water", @"forest", @"wood", @"mountain", @"graveyard", @"river", nil];

    [self.locArray removeAllObjects];

    if (![self queue])
    {
        [self setQueue:[[NSOperationQueue alloc] init]];
    }

    for (int i = 0; i < phrases.count; i++)
    {
        NSURL *url = [dataHelper getURLForSpecialPhrase:phrases[i] withBoundingBox:boundingBox];

        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request setDelegate:self];
        [request setTag:i];
        [request setDidFinishSelector:@selector(requestDone:)];
        [request setDidFailSelector:@selector(requestWentWrong:)];
        [[self queue] addOperation:request];
    }
    [self.queue addObserver:self forKeyPath:@"operations" options:0 context:NULL];
    }
}

1 个答案:

答案 0 :(得分:0)

当您的应用在后台运行时,我不会这样做。您可以做的是在应用程序进入后台模式时预先确定所有2分钟间隔随机数(一段时间,比如说2小时),并为随机数为0的所有时间安排本地计时器。

我不认为用户会因为你的应用在后台运行时每8分钟收到一次本地通知垃圾邮件而感到高兴,顺便说一句......