Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

objective c - iphone - NSTimers in background

Im developing an app that has to run in the background. It's a location based app, so it runs all the time, the OS doesn't kill it.

It should send some info every 10 secs(just for debugging), I set a timer once its in the background. I set a breakpoint in the function that should be executed every 10 secs, which is never called, but if I pause the app and then continue the timer is called, and then the timer is executed every 10 secs without problems, weird right?

I thought that the timer would be executing anyway when I wasn't debugging, but it isn't, same thing as if I didn't pause the debugging.

My question is WHY?? The timer is set correctly(I assume) since it works after pausing, but it's not.

Any ideas?

The way I set the timer is:

self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(doStuff) userInfo:nil repeats:YES];

And in the function I connect to a webservice.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have a similar app design and was stuck on the same thing. What I found somewhere on the internet is adding this type of statement applicationDidEnterBackground:

    UIBackgroundTaskIdentifier locationUpdater =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
         [[UIApplication sharedApplication] endBackgroundTask:locationUpdater];
        locationUpdater=UIBackgroundTaskInvalid;
     } ]; 

This tells the os that you still have things going and not to stop it.

I have my timer attached to this function

 //this is a wrapper method to fit the required selector signature
- (void)timeIntervalEnded:(NSTimer*)timer {
     [self writeToLog:[NSString stringWithFormat:@"Timer Ended On %@",[NSDate date]]];
     [self startReadingLocation];
     [timer invalidate];
     timer=nil;
}

I set the timer in my my location manager delegate methods.

I feel your pain. I found that these things were super finicky. This is what worked for me. I hope it helps. I have found that there isn't any really restrictions in what you can do in the background.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...