Error with timer mm:ss - objective-c

I'm new to objective C.
i've been playing around with a countdown for some time now and i cant seem to make it work.
i've connecting very thing in storyboard and the buttons react, but it seems like its just randomly counting down.
why i isnt it counting down like 10:00 to 09:59.
- (void)showActivity{
int currentTime = [time.text intValue];
int newTime = currentTime - 1;
int seconds = newTime % 60;
int minutes = (newTime / 60) % 60;
time.text = [NSString stringWithFormat:#"%02d:%02d", minutes, seconds];
}

If time.text is "10:00", then calling [time.text intValue] is just going to return the integer 10.
I'd recommend creating a separate variable (perhaps an NSTimeInterval) that keeps track of how many seconds are left, and then make the time text label just responsible for displaying that as minutes:seconds.
e.g.
#property NSTimeInterval time;
#property UILabel *timeLabel; // "time" in your original code
- (void)showActivity {
NSTimeInterval newTime = self.time - 1;
int minutes = floor(newTime / 60);
int seconds = round(newTime - (minutes * 60));
self.timeLabel.text = [NSString stringWithFormat:#"%02d:%02d", minutes, seconds];
self.time = newTime;
}

Related

Millisecond timer in Cocos2d

I have the following code:
-(void)update:(ccTime)delta {
totalTime += delta * 10;
currentTime = (int)totalTime;
if (myTime < currentTime) {
myTime = currentTime;
[timeLabel setString:[NSString stringWithFormat:#"Time: \n%i:%02i:%02i.%i", myTime/36000,(myTime/600)%60,(myTime/10)%60,myTime%10]];
}
}
This code is working good, is there a way to add milliseconds though? And if so, could I have it to the thousandths place: 1:23:45.678
There's no need to use Cocoas2d for this, just use standard Cocoa.
#property CFTimeInterval startTime; // put this in your *.h file
-(void)update:(ccTime)delta {
if (fabs(self.startTime - 0) < 0.1) { // if startTime is close to 0, set it to the current time (cannot do == comparisons with a CFTimeInterval)
self.startTime = CFAbsoluteTimeGetCurrent();
}
CFTimeInterval timeSinceStart = CFAbsoluteTimeGetCurrent() - self.startTime;
int hours = floor(timeSinceStart / 3600);
int minutes = floor(timeSinceStart / 60) - (hours * 60);
double seconds = timeSinceStart - (hours * 3600) - (minutes * 60);
NSLog(#"%02i:%02i:%06.3f", hours, minutes, seconds);
[timeLabel setString:[NSString stringWithFormat:#"Time: \n%02i:%02i:%06.3f", hours, minutes, seconds]];
}

Objective-C: How Can I Format a float value to Only Display The Decimal, Without The Full Figure, or Decimal Point?

There are MANY Q&A's for limiting to only 2 decimal places, to the point of over saturation.
However, I would like to format my float to only get the decimal value.
I'm making a stopwatch, and currently have this...
#implementation HudLayer
{
CCLabelTTF *_label;
float timer;
}
-(void)update:(ccTime)delta { if (_isTimerActive)
{
timer += delta;
NSNumber *theDouble = [NSNumber numberWithDouble:timer];
float miliseconds = timer;
int inputSeconds = [theDouble intValue];
int hours = inputSeconds / 3600;
int minutes = ( inputSeconds - hours * 3600 ) / 60;
NSString *theTime = [NSString stringWithFormat:#"%.2d:%.2d:%.2f", hours, minutes, miliseconds];
[_label setString:[NSString stringWithFormat:#"Time: %#", theTime]];
}
}
However, the issue I'm having is that the timer reads out put on to the label showing the full seconds...
00:14:865.35
Instead it should just be:
00:14:05.35
HH:MM:SS.ms
My first thought was to just drop the decimal from the outputted float, and manually calculate seconds as i do hours and minutes...
Any advice? Thanks...
Try following
timer += delta;
float float_seconds = timer;
int seconds = float_seconds;
int hours = seconds / 3600;
int minutes = seconds / 60 % 60;
NSString *theTime = [NSString stringWithFormat:#"%.2d:%.2d:%05.2f", hours, minutes, float_seconds - ( seconds / 60) * 60];
NSLog(theTime);
[_label setString:[NSString stringWithFormat:#"Time: %#", theTime]];

Getting Video Duration from ALAsset

Hi I'm new to objective C. I'm using AGImagePicker to pick images and video files from phone library and displaying them in GridView. but now I want to get duration of video file to display it with video thumbnail. I don't know how to get video duration from ALAsset. Anybody Please. Any type of answer would be appreciated.
1)To get the Media Duration with the Help of ALAssetPropertyDuration
double value = [[asset valueForProperty:ALAssetPropertyDuration] doubleValue]; //Find the Duraion
[cell.lblMediaLength setText:[self timeFormatted:value]];
2)Method that convert the Total seconds to Hour:min:sec
- (NSString *)timeFormatted:(double)totalSeconds
{
NSTimeInterval timeInterval = totalSeconds;
long seconds = lroundf(timeInterval); // Modulo (%) operator below needs int or long
int hour = 0;
int minute = seconds/60.0f;
int second = seconds % 60;
if (minute > 59) {
hour = minute/60;
minute = minute%60;
return [NSString stringWithFormat:#"%02d:%02d:%02d", hour, minute, second];
}
else{
return [NSString stringWithFormat:#"%02d:%02d", minute, second];
}
}
For Swift
func timeFormatted(totalSeconds: Float64) -> String {
let timeInterval: NSTimeInterval = totalSeconds
let seconds: Int = lround(timeInterval)
var hour: Int = 0
var minute: Int = Int(seconds/60)
let second: Int = seconds % 60
if minute > 59 {
hour = minute / 60
minute = minute % 60
return String(format: "%02d:%02d:%02d", hour, minute, second)
}
else {
return String(format: "%02d:%02d", minute, second)
}
}
If asset is an ALAsset:
NSNumber *number = [asset valueForProperty:ALAssetPropertyDuration];
This will return an NSNumber. If you want the value:
double value = [[asset valueForProperty:ALAssetPropertyDuration] doubleValue];
Here is how I get the duration.
AVAsset *testAsset = [AVAsset assetWithURL:url];
return testAsset.duration;

Objective-c format time left until certain date

I'm creating a countdown timer and I need to printout the time left (hour:minute:seconds) until a specific date. I've found how to get the time interval between Now and the target date but I don't know how to format the time interval as a string. Does NSDateFormater work on NSTimeInterval?
NSTimeInterval is in seconds, use divide and remainder to break it up and format (code untested):
NSString *timeIntervalToString(NSTimeInterval interval)
{
long work = (long)interval; // convert to long, NSTimeInterval is *some* numeric type
long seconds = work % 60; // remainder is seconds
work /= 60; // total number of mins
long minutes = work % 60; // remainder is minutes
long hours = work / 60 // number of hours
// now format and return - %ld is long decimal, %02ld is zero-padded two digit long decimal
return [NSString stringWithFormat:#"%ld:%02ld:%02ld", hours, minutes, seconds];
}
You would first compare two NSDate objects to retrieve the difference in seconds between the two, the NSDate method you should use is
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
Then you could simply write a function to parse the seconds into hours/minutes/seconds, for example you could use this (untested):
-(NSDictionary*)createTimemapForSeconds:(int)seconds{
int hours = floor(seconds / (60 * 60) );
float minute_divisor = seconds % (60 * 60);
int minutes = floor(minute_divisor / 60);
float seconds_divisor = seconds % 60;
seconds = ceil(seconds_divisor);
NSDictionary * timeMap = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInt:hours], [NSNumber numberWithInt:minutes], [NSNumber numberWithInt:seconds], nil] forKeys:[NSArray arrayWithObjects:#"h", #"m", #"s", nil]];
return timeMap;
}
This is code from my project:
-(NSString*)timeLeftString
{
long seconds = [self msLeft]/1000;
if( seconds == 0 )
return #"";
if( seconds < 60 )
return [NSString stringWithFormat:
pluralString(seconds,
NSLocalizedString(#"en|%ld second left|%ld seconds left", #"")), seconds];
long minutes = seconds / 60;
seconds -= minutes*60;
if( minutes < 60 )
return [NSString stringWithFormat:
NSLocalizedString(#"%ld:%02ld left",#""),
minutes, seconds];
long hours = minutes/60;
minutes -= hours*60;
return [NSString stringWithFormat:
NSLocalizedString(#"%ld:%02ld:%02ld left",#""),
hours, minutes, seconds];
}
msLeft --- my function that returns time in milliseconds
pluralString --- my function that provides different parts of format string depending on the value (http://translate.sourceforge.net/wiki/l10n/pluralforms)
Function returns different format for different timer values (1 second left, 5 seconds left, 2:34 left, 1:15:14 left).
In any case, progress bad should be visible during long operation
One more thought: In case that time left is "small" (less then a minute?), probably time left should not be shown --- just progress bar left to reduce interface "visual noise".

Objective-c Method to get a number then countdown in 1 every second

i need a little help i have a method which gets value such as 50, it then assigns that value to trackDuration, so NSNumber *trackDuration = 50, i want the method to every second minus 1 from the value of trackDuration and update a label, the label being called duration.
Here's what i have so far;
- (void) countDown {
iTunesApplication *iTunes = [SBApplication applicationWithBundleIdentifier:#"com.apple.iTunes"];
NSNumber *trackDuration = [NSNumber numberWithDouble:[[iTunes currentTrack] duration]];
while (trackDuration > 0) {
trackDuration - 1;
int inputSeconds = [trackDuration intValue];
int hours = inputSeconds / 3600;
int minutes = ( inputSeconds - hours * 3600 ) / 60;
int seconds = inputSeconds - hours * 3600 - minutes * 60;
NSString *trackDurationString = [NSString stringWithFormat:#"%.2d:%.2d:%.2d", hours, minutes, seconds];
[duration setStringValue:trackDurationString];
sleep(1);
}}
Any help would be much appreciated, thanks in advanced, Sami.
This will block the main thread, and you are not assigning the value trackDuration, so it will always stay 50
trackDuration -1;
Should be:
trackDuration--; // or trackDuration -= 1;
Also I would do it like this:
- (void)startCountDown
{
[NSTimer scheduledTimerWithInterval:1.0f target:self selector:#selector(timerHit:) userInfo:nil repeats:YES];
}
- (void)timerHit:(NSTimer *)p_timer
{
if( trackDuration <= 1 && [p_timer isValid] )
[p_timer invalidate];
// track duration is an instance variable
trackDuration--;
// update LABEL
}
iOS 2.x or higher is required for NSTimer
Having this method run in a loop will make your app go unresponsive for the whole time it's running — you won't even see any UI updates. Instead, you should use an NSTimer with an interval of one second, and update the elapsed time when the timer fires.