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
868 views
in Technique[技术] by (71.8m points)

ios - How to maintain Timer to continue running when Home button is pressed

I have done research how to maintain the timer running when home button is pressed. But i am quite confused.

This is my code, how can i fix it and the timer continue running in background? Thanks in advance.

-(id)init {

if (self = [super init]) {
    self.timer = [[NSTimer alloc] init];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];
}
return self;
}

+(Timer *)sharedSingleton {

static Timer *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    sharedSingleton = [[Timer alloc] init];
});
return sharedSingleton;
}

-(void)startTimer {


i++;
_count = [NSNumber numberWithInteger:i];
[[NSNotificationCenter defaultCenter] postNotificationName:COUNT object:_count];
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
NSTimer *timer;
- (void)viewDidLoad {
    [super viewDidLoad];

    UIBackgroundTaskIdentifier backgroundTaskIdentifire =0;

    UIApplication  *application = [UIApplication sharedApplication];
    backgroundTaskIdentifire = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:backgroundTaskIdentifire];
    }];


    timer = [NSTimer
             scheduledTimerWithTimeInterval:1.0
             target:self
             selector:@selector(yourFunction)
             userInfo:nil
             repeats:YES];
}

-(void)yourFunction{

    NSLog(@"Timer");
}

Marks the beginning of a new long-running background task. A unique identifier for the new background task. You must pass this value to the endBackgroundTask: method to mark the end of this task. This method returns UIBackgroundTaskInvalid if running in the background is not possible.

Parameter taskName The name to display in the debugger when viewing the background task. If you specify nil for this parameter, this method generates a name based on the name of the calling function or method. handler A handler to be called shortly before the app’s remaining background time reaches 0. You should use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the app. The handler is called synchronously on the main thread, blocking the app’s suspension momentarily while the app is notified.


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

...