Resume timer after pausing it? - ios

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;
}

Related

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);
}

UI Date Picker not Displaying in Label

When I go to a viewcontroller in my app, I have two date pickers. Both of which have labels, and if either one is moved they update accordingly.
The start date is set to automatically be today's date. While it saves to Core Data just fine it doesn't display in the label unless I change it to a different day.
Basically when I load that screen the label should have today's date, and change if I change it in the date picker.
I figure it's something simple overlooking, but I can't figure out what it is, any help would be appreciated.
- (void)viewDidLoad
{
[super viewDidLoad];
svos = self.scrollView.contentOffset;
[self.startDate addTarget:self action:#selector(datePickerChanged:) forControlEvents:UIControlEventValueChanged];
[self.endDate addTarget:self action:#selector(datePickerChanged1:) forControlEvents:UIControlEventValueChanged];
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
if(!appDelegate.dateProductionDroneStartDate)
[self.startDate setDate:[NSDate date]];
else
{
[self.startDate setDate:appDelegate.dateProductionDroneStartDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yyyy "];
NSString *strDate = [dateFormatter stringFromDate:self.startDate.date];
self.productionDroneStartDate.text = strDate;
}
NSDate *now = [NSDate date];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:now options:0];
if(!appDelegate.dateProductionDroneEndDate)
[self.endDate setDate:newDate2];
else
{
[self.endDate setDate:appDelegate.dateProductionDroneEndDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yyyy "];
NSString *strDate = [dateFormatter stringFromDate:self.endDate.date];
self.productionDroneEndDate.text = strDate;
}
self.txtProductionName.text = appDelegate.strProductionName;
self.txtProductionScene.text = appDelegate.strProductionScene;
self.txtProductionReel.text = appDelegate.strProductionReel;
self.txtProductionName.delegate = self;
self.txtProductionReel.delegate = self;
self.txtProductionScene.delegate = self;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
}
SO far what I got from ur question and code, simple mistake is as below :-
- (void)viewDidLoad
{
[super viewDidLoad];
....
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yyyy "];
NSString *strDate = [dateFormatter stringFromDate:self.startDate.date];
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
if(!appDelegate.dateProductionDroneStartDate) //As initially this will be true and current date will be set.
[self.startDate setDate:[NSDate date]];
//So as you set the current date in self.startDate but not in label.
//Added below line for setting your label
else
{
[self.startDate setDate:appDelegate.dateProductionDroneStartDate];
}
self.productionDroneStartDate.text = strDate;
......
}
This should get you working further.
Why can't you just set the label with todays date at start without even touching the Picker. Then when the picker is moved as you suggest the label will be updated as expected.

How to correctly generate timestamp

I have a method that to create timestamp in long long integer format
EX: 1386752892
+ (NSNumber *)currentTimestampWithLongLongFormat
{
double timeStamp = ceil([[NSDate date] timeIntervalSince1970] * 1000);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setGeneratesDecimalNumbers:false];
NSNumber *timeNumber = [NSNumber numberWithDouble:timeStamp];
NSString *timeString = [formatter stringFromNumber:timeNumber];
// NSTimeInterval is defined as double
return [NSNumber numberWithLongLong:[timeString longLongValue]];
}
But this will generate 13 digitals number
EX: 1386752811802
How to fix the problem and generate the correct format of number?
int timestamp = [[NSDate date] timeIntervalSince1970];
Try this
/**
* #param nil
* #return current time in mili second
*
* Fetch the current time stamp
*/
-(NSString *)currentTimeStamp {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithName:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp1 = [dateFormatter stringFromDate:[NSDate date]];
NSDate *curdate = [dateFormatter dateFromString:timeStamp1];
double unix_timestamp = [curdate timeIntervalSince1970];
NSString *timeStamp = [NSString stringWithFormat:#"%f",unix_timestamp*1000];
return timeStamp;
}
+ (NSString*) dateFromString:(NSString*)aStr
{
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
[formater setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *date2 = [formater dateFromString:aStr];
[formater setDateFormat:#"d MMM,yyyy HH:mm"];
NSString *result = [formater stringFromDate:date2];
return result;
}
+ (NSString *)calculateTime:(NSString *)datetime :(NSString *)servertime
{
NSString *time;
NSDate *date1;
NSDate *date2;
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
date1 = [formatter dateFromString:datetime];
date2 = [formatter dateFromString:servertime];
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *differenceComponents = [calendar components:(NSDayCalendarUnit)
fromDate:date1
toDate:date2
options:0];
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];//[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
int hour = interval / 3600;
int minute = (int)interval % 3600 / 60;
int seconds = (int)interval % 60;
hour=ABS(hour);
minute=ABS(minute);
seconds=ABS(seconds);
if ([differenceComponents day]>0) {
time= [NSString stringWithFormat:#"%ld %#", (long)[differenceComponents day],[NSString stringWithFormat:NSLocalizedString(#"daysago", nil)]];
}
else
{
if ([differenceComponents day] == 0) {
time= [NSString stringWithFormat:#"%ld %#", (long)[differenceComponents day],[NSString stringWithFormat:NSLocalizedString(#"dayago", nil)]];
if (hour>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(hour),[NSString stringWithFormat:NSLocalizedString(#"hourago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(hour),[NSString stringWithFormat:NSLocalizedString(#"hoursago", nil)]];
if (minute>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(minute),[NSString stringWithFormat:NSLocalizedString(#"minuteago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(minute),[NSString stringWithFormat:NSLocalizedString(#"minuteago", nil)]];
if (seconds>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(seconds),[NSString stringWithFormat:NSLocalizedString(#"secondago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(seconds),[NSString stringWithFormat:NSLocalizedString(#"secondsago", nil)]];
}
}
}
}
}
return time;
}
/// as per requirement we will use date formats

Timer won't stop after 45 minutes

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.

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