swift NSTimer in Background

You shouldn’t be messing with any adjustments based upon when it enters background or resumes, but rather just save the time that you are counting from or to (depending upon whether you are counting up or down). Then when the app starts up again, you just use that from/to time when reconstructing the timer. Likewise, … Read more

How can I make a countdown with NSTimer?

In Swift 5.1 this will work: var counter = 30 override func viewDidLoad() { super.viewDidLoad() Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true) } @objc func updateCounter() { //example functionality if counter > 0 { print(“\(counter) seconds to the end of the world”) counter -= 1 } }

How do I create a NSTimer on a background thread?

If you need this so timers still run when you scroll your views (or maps), you need to schedule them on different run loop mode. Replace your current timer: [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; With this one: NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; For details, check this … Read more

How to Pause/Play NSTimer?

Try this shizzle… worked great for me EDIT To be honest my actual code is this: -(IBAction)clicked:(id)sender { if ([startStop.titleLabel.text isEqualToString:@”Start”]) { [startStop setTitle:@”Pause” forState:UIControlStateNormal]; [startStop setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countUp) userInfo:nil repeats:YES]; timerDown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES]; } else if ([startStop.titleLabel.text isEqualToString:@”Pause”]) { [startStop setTitle:@”Resume” forState:UIControlStateNormal]; [startStop … Read more

What’s the best way to detect when the app is entering the background for my view?

You can have any class interested in when the app goes into the background receive notifications. This is a good alternative to coupling these classes with the AppDelegate. When initializing said classes: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil]; Responding to the notifications -(void)appWillResignActive:(NSNotification*)note { } -(void)appWillTerminate:(NSNotification*)note { [[NSNotificationCenter defaultCenter] … Read more

tech