Timer won't stop after 45 minutes - ios

I have this NSTimer that I want it to stop after 45 minutes, but it won't stop.
What am I doing wrong?
TIMER_COUNT = 45
HOURS_IN_HOURS = 60
HOURS_IN_DAY = 24
- (void)start
{
self.timerCountdown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats: YES];
}
- (void)stop
{
[self.timerCountdown invalidate];
self.timerCountdown = nil;
}
- (void)updateCountdown
{
NSDate *currentDate = [NSDate date];
NSDate *finalTime = [currentDate dateByAddingTimeInterval:(TIMER_COUNT * HOURS_IN_HOUR)];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsHours = [calendar components:NSHourCalendarUnit fromDate:currentDate];
NSDateComponents *componentMinuts = [calendar components:NSMinuteCalendarUnit fromDate:currentDate];
NSDateComponents *componentSeconds = [calendar components:NSSecondCalendarUnit fromDate:currentDate];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSDayCalendarUnit
fromDate:currentDate
toDate:finalTime
options:0];
NSLog(#"%20d Days, %02d Hours, %02d Minutes, %02d Seconds.", componentsDaysDiff.day, HOURS_IN_DAY - componentsHours.hour, HOURS_IN_HOUR - componentMinuts.minute, HOURS_IN_HOUR - componentSeconds.second);
if ([currentDate compare:finalTime] == NSOrderedSame)
{
NSLog(#"Done.");
[self stop];
}
}
Thanks in advance.

Because your currentDate will keep being set every time your timer ticks. [NSDate date] will set currentDate to the current time every time the updateCountdown method runs. Therefore will finalTime always be 45 minutes ahead of currentDate. You should create a startDate property and set it in the start method instead:
- (void)start
{
self.timerCountdown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats: YES];
self.startDate = [NSDate date];
}
Then check on the property in the updateCountdown method:
if ([self.startDate compare:finalTime] == NSOrderedSame)
{
NSLog(#"Done.");
[self stop];
}
Alternatively you can use an integer with the number of ticks you are expecting and then substract one from the integer everytime the timer ticks.
Something like this:
- (void)start
{
self.timerCountdown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateCountdown) userInfo:nil repeats:YES];
self.countdown = TIMER_COUNT * HOURS_IN_HOUR;
}
- (void)updateCountdown
{
self.countdown--;
//your code
if (self.countdown == 0)
{
NSLog(#"Done.");
[self stop];
}
}

- (void)start {
NSString *startTime = [NSDate date];
NSDateComponents *durationComponents = [[[NSDateComponents alloc] init] autorelease];
durationComponents.minutes = 45;
NSCalendar *gregorianCalendar = [NSCalendar currentCalendar];
self.endTime = [calendar dateByAddingComponents:durationComponents
toDate:startTime
options:0];
self.timerCountdown = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(updateCountdown)
userInfo:nil
repeats:YES];
}
- (void)stop {
[self.timerCountdown invalidate];
self.timerCountdown = nil;
}
- (void)updateCountdown {
NSDate *currentTime = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *currentTimeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit)
fromDate:currentTime];
if ([currentTime compare:self.endTime] == NSOrderedDescending) {
[self stop];
}
}

You don't need the startDate property.
And you should not check dates for equality. That is very unlikely to happen.
Use that comparison:
if ([finalTime compare:[NSDate date]] == NSOrderedAscending)
{
NSLog(#"Done.");
[self.timerCountdown invalidate];
[self stop];
}
This means that finalTime is earlier in time than current time.

Related

Change random image every midnight

I'm have some images on the app and I want that the image change random every day at midnight.
I've tried unsuccessfully to do that in the code below, but can't figure how to make it work.
- (void)viewDidLoad
{
[super viewDidLoad];
NSDateFormatter *formater = [[NSDateFormatter alloc]init];
[formater setDateFormat:#"EEE dd-MM-yyyy' "];
timeLabel.text = [formater stringFromDate:[NSDate date]];
timerIsCount = NO;
[self updateTimer];
}
-(void)datePic
{
timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(randomCard) userInfo:nil repeats:YES];
}
- (void)updateTimer
{
NSCalendar *calender = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlag = NSDayCalendarUnit;
NSDateComponents *components = [calender components:unitFlag fromDate:0];
int day = [components day];
if (day) {
//[self randomCard];
}
}
Here you have to a take array of images. And one int value.
You want every night your image will change, so you have to set timer
Here Slidingimageview is imageview
NSInteger index=0;
arrslidingimages=[[NSArray alloc]initWithObjects:#"01.png",#"02.png",#"03.png",#"04.png",#"05.png"#"06.png",#"07.png",nil];
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// Animation of sliding image
slideTransition = [CATransition animation];
CATransition * slideTransition; //instance variable
slideTransition.duration = 1.0;
slideTransition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
slideTransition.type = kCATransitionFade;
slideTransition.delegate = self;
[NSTimer scheduledTimerWithTimeInterval:60*60*24 target:self selector:#selector(changeImage:) userInfo:nil repeats:YES];
}
-(void)changeImage:(NSTimer *)timer
{
//change timer of the sling image and set the current page of page controller
slideTransition.subtype =kCATransitionFromRight; // or kCATransitionFromRight
[_Slidingimageview.layer addAnimation:slideTransition forKey:nil];
index++;
if(index==[arrslidingimages count]){
index=0;
}
_Slidingimageview.image = [UIImage imageNamed:[arrslidingimages objectAtIndex:index]];
}
You have to set timer of midnight by finding time in seconds. If you want more random images then Add those images in array
NOTE: Right now in code I set default value like when u run app this timer starts(EXA. If you run app at 12:00 AM today then image will change at 12:00 AM tomorrow)
Hope this thing Works

How to display timer in reverse on a label in xcode? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
i have a view controller in that i want to display time in reverse order.my default time is 00:59:59? i want output like this (00:58:00,00:57:00,00:56:00,00:30:00)?
int currentTimeInSeconds;
NSTimer *myTimer;
if (!timeLabel)
{
timeLabel =0;
}
if (!myTimer)
{
myTimer = [self createTimer];
}
-(NSTimer *)createTimer
{
return [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerTicked) userInfo:nil repeats:YES];
}
-(void)timerTicked
{
if (currentTimeInSeconds == 0)
{
[myTimer invalidate];
currentTimeInSeconds = 60;
timeLabel.text = [self formattedTime:currentTimeInSeconds];
}
else
{
currentTimeInSeconds--;
self.timeLabel.text = [self formattedTime:currentTimeInSeconds];
}
}
-(NSString *)formattedTime:(int)totalSeconds
{
int seconds = totalSeconds%60;
int minutes = (totalSeconds/60)%60;
int hours = totalSeconds/3600;
return [NSString stringWithFormat:#" %02d:%02d:%02d",hours,minutes,seconds];
}
- (IBAction)btnStart:(id)sender {
timet=[self.txtTime.text integerValue];
self.lblTime.text=[NSString stringWithFormat:#"%lu", (unsigned long)timet];
[NSTimer scheduledTimerWithTimeInterval:timet
target:self
selector:#selector(targetMethod)
userInfo:nil
repeats:NO];
[self time];
}
-(void)time
{
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(targetMethod2)
userInfo:nil
repeats:NO];
}
-(void)targetMethod
{
NSLog(#"STOP");
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Stop" message:#"Time is over" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];//, nil
[alert show];
}
-(void)targetMethod2
{
if(timet!=0)
{
timet-=1;
NSLog(#"%lu",(unsigned long)timet);
self.lblTime.text=[NSString stringWithFormat:#"%lu",(unsigned long)timet];
[self time];
}
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
self.txtTime.text=nil;
self.lblTime.text=nil;
}
}
---------------- Second code ---------------------
#interface ViewController ()
{
UILabel *progress;
NSTimer *timer;
int currMinute;
int currSeconds;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
progress=[[UILabel alloc] initWithFrame:CGRectMake(80, 15, 100, 50)];
progress.textColor=[UIColor redColor];
[progress setText:#"Time : 3:00"];
progress.backgroundColor=[UIColor clearColor];
[self.view addSubview:progress];
currMinute=3;
currSeconds=00;
[self start];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)start
{
timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(timerFired) userInfo:nil repeats:YES];
}
-(void)timerFired
{
if((currMinute>0 || currSeconds>=0) && currMinute>=0)
{
if(currSeconds==0)
{
currMinute-=1;
currSeconds=59;
}
else if(currSeconds>0)
{
currSeconds-=1;
}
if(currMinute>-1)
[progress setText:[NSString stringWithFormat:#"%#%d%#%02d",#"Time : ",currMinute,#":",currSeconds]];
}
else
{
[timer invalidate];
}
}
- (IBAction)startCountdown:(id)sender {
//Set up a timer that calls the updateTime method every second to update the label
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(updateCounterLabel)
userInfo:nil
repeats:YES];
}
Every 1 Sec call following function.
-(void)timerTicked
{
NSString *dateString = #"12-12-2015";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsHours = [calendar components:NSHourCalendarUnit fromDate:now];
NSDateComponents *componentMint = [calendar components:NSMinuteCalendarUnit fromDate:now];
NSDateComponents *componentSec = [calendar components:NSSecondCalendarUnit fromDate:now];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSDayCalendarUnit
fromDate:now
toDate:dateFromString
options:0];
long day = (long)componentsDaysDiff.day;
long hours = (long)(24-componentsHours.hour);
long minutes = (long)(60-componentMint.minute);
long sec = (long)(60-componentSec.second);
NSString *strForday = [NSString stringWithFormat:#"%02ld",day];
NSString *strForhours = [NSString stringWithFormat:#"%02ld",hours];
NSString *strForminutes = [NSString stringWithFormat:#"%02ld",minutes];
NSString *strForsec = [NSString stringWithFormat:#"%02ld",sec];
NSLog(#"%# %# %# %# ",strForday,strForhours,strForminutes,strForsec);
if (day == 0 && hours == 0 && minutes == 0 && sec == 0) {
[myTimer invalidate];
}
}

resume function does not work correctly in NSTime

I have a NSTimer that functions as a stopwatch. It makes the time count and has the pause function that works properly but the function does not work continue. The timer seems to be counting even paused but not updated the label and when I touch the button comes down to is to continue from where you left it continues counting that did not stop. How can I fix this?
this is my chronometer code:
- (void)viewDidLoad {
[super viewDidLoad];
[self setUp];
self.isPaused = NO;
}
- (void) setUp {
startDate = [NSDate date];
_timer = [NSTimer scheduledTimerWithTimeInterval: 1.0/100.0 target: self selector: #selector(timerUpdating) userInfo: nil repeats: true];
}
-(void)timerUpdating {
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormater = [[NSDateFormatter alloc]init];
[dateFormater setDateFormat:#"mm:ss"];
[dateFormater setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString = [dateFormater stringFromDate:timerDate];
if (self.isPaused == NO){
_timerLabel.text = timeString;
}
}
- (IBAction)pauseAction:(id)sender {
[self pauseTimer:self.timer];
}
- (IBAction)resumeAction:(id)sender {
[self resumeTimer:self.timer];
}
-(void) pauseTimer:(NSTimer *)timer {
self.isPaused = YES;
self.pauseStart = [NSDate date];
self.previousFireDate = [timer fireDate];
[timer setFireDate:[NSDate distantFuture]];
}
-(void) resumeTimer:(NSTimer *)timer {
self.isPaused = NO;
NSDate *currentDate = [NSDate date];
NSTimeInterval pauseTime = [currentDate timeIntervalSinceDate:pauseStart];
NSDate *neededFireDate = [NSDate dateWithTimeInterval:pauseTime sinceDate:previousFireDate];
[timer setFireDate:neededFireDate];
NSLog(#"Fire Date: %#", timer.fireDate);
}
At timerUpdating you set NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];. This will not take into account if the user paused the timer or not.
To correct this behavior you could do something like:
In .h (set a member variable):
NSTimeInterval pausedTime;
In .m (3 lines edited)
- (void)viewDidLoad {
[super viewDidLoad];
[self setUp];
self.isPaused = NO;
pausedTime = 0; //edit
}
- (void) setUp {
startDate = [NSDate date];
_timer = [NSTimer scheduledTimerWithTimeInterval: 1.0/100.0 target: self selector: #selector(timerUpdating) userInfo: nil repeats: true];
}
-(void)timerUpdating {
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate] - pauseTime;//edit
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormater = [[NSDateFormatter alloc]init];
[dateFormater setDateFormat:#"mm:ss"];
[dateFormater setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString = [dateFormater stringFromDate:timerDate];
if (self.isPaused == NO){
_timerLabel.text = timeString;
}
}
- (IBAction)pauseAction:(id)sender {
[self pauseTimer:self.timer];
}
- (IBAction)resumeAction:(id)sender {
[self resumeTimer:self.timer];
}
-(void) pauseTimer:(NSTimer *)timer {
self.isPaused = YES;
self.pauseStart = [NSDate date];
self.previousFireDate = [timer fireDate];
[timer setFireDate:[NSDate distantFuture]];
}
-(void) resumeTimer:(NSTimer *)timer {
self.isPaused = NO;
NSDate *currentDate = [NSDate date];
NSTimeInterval pauseTime = [currentDate timeIntervalSinceDate:pauseStart];
pausedTime += pauseTime;//edit
NSDate *neededFireDate = [NSDate dateWithTimeInterval:pauseTime sinceDate:previousFireDate];
[timer setFireDate:neededFireDate];
NSLog(#"Fire Date: %#", timer.fireDate);
}

Resume timer after pausing it?

I've looked at the other pause/resume timer questions but couldn't figure out how to fix my problem. I just have a simple timer label and two buttons, a start and a stop button. Let me know if you need any more info on my project to help answer my question. Can anyone see where I'm going wrong?
- (void)updateTimer
{
// Create date from the elapsed time
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:self.startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
// Create a date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormatter stringFromDate:timerDate];
self.stopwatchLabel.text = timeString;
}
- (void)updateResumeTimer
{
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormat stringFromDate:dateFor];
self.stopwatchLabel.text = timeString;
}
- (IBAction)onStartPressed:(id)sender {
NSString *isItEqual = self.stopwatchLabel.text;
if ([isItEqual isEqualToString:#"00:00:00"]) {
self.startDate = [NSDate date];
// Create the stop watch timer that fires every 10 ms
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
}
else {
// Create the stop watch timer that fires every 10 ms
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateResumeTimer)
userInfo:nil
repeats:YES];
}
}
- (IBAction)onStopPressed:(id)sender {
resumeText = self.stopwatchLabel.text;
NSLog(#"Timer is %#", resumeText);
dateFormat=[[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"HH:mm:ss"];
dateFor=[dateFormat dateFromString:resumeText];
[dateFormat setDateFormat:#"HH:mm:ss"];
[self.stopWatchTimer invalidate];
self.stopWatchTimer = nil;
[self updateTimer];
}
You will need to add a property
#property (assign, nonatomic) NSTimeInterval previousTimeInterval;
Just copy the below lines of code and it should work.
- (void)updateTimer
{
// Create date from the elapsed time
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:self.startDate];
timeInterval += self.previousTimeInterval;
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
self.dateFor = timerDate;
// Create a date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormatter stringFromDate:timerDate];
self.stopwatchLabel.text = timeString;
}
- (IBAction)onStartPressed:(id)sender {
self.startDate = [NSDate date];
// Create the stop watch timer that fires every 10 ms
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
//Disable start button and enable stop
self.startButton.enabled = NO;
self.stopButton.enabled = YES;
}
- (IBAction)onStopPressed:(id)sender
{
[self.stopWatchTimer invalidate];
self.stopWatchTimer = nil;
self.previousTimeInterval = [self.dateFor timeIntervalSince1970];
// enable start button and disable stop button
self.startButton.enabled = YES;
self.stopButton.enabled = NO;
}

How can I make a countdown from the current date to a specific NSDate?

I want to have a countdown from the current time to a specific date and display that value in a label. I looked at some NSTimer tutorials but I could not figure out how to apply them to my situation.
NSTimeInterval TimeInterval = [aString doubleValue];
NSDate* upperDate = [aDate dateByAddingTimeInterval:TimeInterval];
NSDate* Today = [NSDate date];
//cell.myLabel.text = here i should write a countdown.
Sorry for insufficient code. I usually try to write some of my own code before asking a question here but this time I could not figure what to write.
Edit
So with the answer of PartiallyFinite i figured how i set timer. But because i am using tableview i could not implement the repeat message for MyTimerLabel. Here what i just did:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MyCell";
MekanListesiViewCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MyCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
aClass *aC = [myArray objectAtIndex:indexPath.row];
NSTimeInterval TimeInterval = [aC.aTimeIntervalwithString doubleValue];
NSDate* UpperDate = [aC.aNSDate dateByAddingTimeInterval:TimeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:[NSDate date] toDate:UpperDate options:0];
NSInteger days = [dateComponents day];
NSInteger months = [dateComponents month];
NSInteger years = [dateComponents year];
NSInteger hours = [dateComponents hour];
NSInteger minutes = [dateComponents minute];
NSInteger seconds = [dateComponents second];
NSString *countdownText = [NSString stringWithFormat:#"%d Days %d:%d:%d", days, hours, minutes, seconds];
cell.countdownText= countdownText;
[self performSelector:#selector(updateCoundown)]; // The delay is in seconds, make it whatever you want.
return cell;
}
At myCellView.h
#interface MekanListesiViewCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *MyTimerLabel;
#property(weak)NSString *countdownText;
at myCellView.m
-(void)updateCoundown{
MyTimerLabel.text = countdownText;
[self performSelector:#selector(updateCoundown) withObject:nil afterDelay:1];
}
i get nothing in the MyTimerLabel.
Using the code from this answer (copy pasted below for completeness of example) to get the individual components of the countdown period:
- (void)updateCountdown {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd"];
NSDate *startingDate = [dateFormatter dateFromString:#"2005-01-01"];
NSDate *endingDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];
NSInteger days = [dateComponents day];
NSInteger months = [dateComponents month];
NSInteger years = [dateComponents year];
NSInteger hours = [dateComponents hour];
NSInteger minutes = [dateComponents minute];
NSInteger seconds = [dateComponents second];
We can then create a string with all of these numbers:
NSString *countdownText = [NSString stringWithFormat:#"%d Years %d Months %d Days %d Hours %d Minutes %d Seconds", days, months, years, hours, minutes, seconds];
cell.myLabel.text = countdownText;
Then, we can use performSelector:withObject:afterDelay: to make this method get called again after the specified delay (note that the delay is in seconds):
[self performSelector:#selector(updateCountdown) withObject:nil afterDelay:1];
}
Declare member variables like
NSDate *startDate,*EndDate;
unsigned long countDownSeconds;
According to your requirement
-(void)setUpCountDown{
startDate = [NSDate date]; //Current time
NSDate *endDate = [startDate dateByAddingTimeInterval:10000]; //some future date
NSTimeInterval milliseconds = [endDate timeIntervalSinceDate:startDate];/////will give time in milliseconds
countDownSeconds = (unsigned long)milliseconds/1000;
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(countDown:) userInfo:nil repeats:YES];
}
-(void)countDown:(NSTimer *)timer{
if (countDownSeconds<=0) {
[timer invalidate];
timer = nil;
}
NSLog(#"Time Elapsed in seconds %d", countDownSeconds);
countDownSeconds--;
}
let formatter = NSDateFormatter()
let userCalendar = NSCalendar.currentCalendar()
let requestedComponent: NSCalendarUnit = [
//NSCalendarUnit.Month,
//NSCalendarUnit.Day,
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Second
]
func printTime() {
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let startTime = NSDate()
let endTime = formatter.dateFromString("12/25/16 8:00:00 a")
let timeDifference = userCalendar.components(requestedComponent, fromDate: startTime, toDate: endTime!, options: [])
self.TimeLabel.text = " \(timeDifference.hour)Hours \(timeDifference.minute)Minutes \(timeDifference.second) Seconds"
}
//Put this in your initialiser
let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(myProject.printTime), userInfo: nil, repeats: true)
timer.fire()
I know this thread is very old, but this is how i would do it in Swift
Keep an instance variable to hold the date
//Fire Timer
_savedDate = [[NSDate date]dateByAddingTimeInterval:30];
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(countDown:) userInfo:nil repeats:YES];
- (void)countDown:(NSTimer *)timer
{
NSDate *date = [NSDate date];
if ([date isEqualToDate:_savedDate]) {
[timer invalidate];
}
NSDateComponents *dateComponents = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:date toDate:_savedDate options:0];
NSLog(#"%02d:%02d:%02d",dateComponents.hour,dateComponents.minute,dateComponents.second);
}

Resources