Question

I know there are some questions on this here but my problem is a bit different from them which is why i am asking this question. At the moment i have a NSTimer which is firing every 2 minutes. When the timer was fired there is a 25% chance that my method will be called (it is for a game). For example my NSTimer fires, now a random number is generated from 0-3. If this random number equals 0 then my method should be called. The exact same behavior i'd like to have when my app goes into background mode. When the NSTimer is fired the random number should be generated and if this number equals to 0 then a UILocalNotification should be posted.

My code at the moment looks like this:

    - (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];
    }
}
Était-ce utile?

La solution

I would not do this when your app is running in the background. What you could do is to determine all the 2 minute interval random numbers beforehand (for a certain period of time, say 2 hours) when the app is going to background mode, and schedule local timers for all the times the random number is 0.

I don't think users will be happy if they get spammed with local notifications every 8 minutes while your app is running in the background, by the way ...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top