iOS Timer executado em segundo plano
Meu aplicativo requer chamar um método periodicamente.
Essa chamada deve ser feita mesmo que o aplicativo tenha sido colocado em segundo plano.
O horário em que o aplicativo pode estar em segundo plano é indefinido, sempre que o aplicativo puder deixar de estar em segundo plano para continuar.
Eu tenho uma turma para gerenciar o timer:
@protocol TimerDelegate <NSObject>
- (void)startTimerAction:(id)userInfo;
@end
@interface TimerController : NSObject{
NSTimer *repeatingTimer;
id <TimerDelegate> delegate;
}
+ (TimerController *)sharedInstance;
- (void)startTimerForSender:(id <TimerDelegate>)sender withTimeInterval:(NSTimeInterval)time;
- (void)stopTimer;
@end
Implementação:
#import "TimerController.h"
TimerController *singletonInstance;
@implementation TimerController
#pragma mark - Singleton
+ (TimerController *)sharedInstance {
if (singletonInstance == nil) {
singletonInstance = [[super allocWithZone:NULL] init];
}
return singletonInstance;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
#pragma mark - Public
- (void)startTimerForSender:(id <TimerDelegate>)sender withTimeInterval:(NSTimeInterval)time
{
if (repeatingTimer) {
[self stopTimer];
}
if (sender) {
delegate = sender;
}
if (time > 0.0) {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(targetMethod:)
userInfo:[self userInfo] repeats:YES];
repeatingTimer = timer;
}
}
- (void)stopTimer
{
if (repeatingTimer) {
[repeatingTimer invalidate];
repeatingTimer = nil;
}
}
- (NSDictionary *)userInfo
{
return @{@"StartDate" : [NSDate date]};
}
- (void)targetMethod:(NSTimer*)theTimer
{
if (delegate && [delegate respondsToSelector:@selector(startTimerAction:)]) {
[delegate startTimerAction:[repeatingTimer userInfo]];
}
}
@end
Eu uso oTimerController
classe desta maneira:
-(void)viewDidLoad{
[super viewDidLoad]
TimerController *timerC = [TimerController sharedInstance];
[timerC startTimerForSender:self withTimeInterval:30];
}
#pragma mark - TimerDelegate
- (void)startTimerAction:(id)userInfo
{
NSLog(@"Method called");
}
Eu posso lerNSLog
entradas a cada 30 segundos. Colocar o aplicativo em segundo plano faz com que o temporizador pare e não grave logs a cada 30 segundos, quando o aplicativo retomar o cronômetro funciona corretamente.
Preciso chamar o método a cada 30 segundos, embora o aplicativo esteja em segundo plano.
Eu li esta pergunta:Temporizador no modo de fundo
Eu devo ser capaz de enviar o aplicativo para a AppStore.
obrigado