I am having a label and an array which consists of 10 string values.I know how to display the text in that label.But now,For every 1 minutes I want to display each and every string from that array to the label .Any idea how to do this ?
Use an NSTimer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:#selector(changeText:) userInfo:nil repeats:YES];
Remember to use [timer invalidate] if you want to stop the timer, or you'll have a crash if the target has been released.
Add a variable in your class to save the index of current string
Write a method which increase the index and update the label with the next string
Create a NSTimer with interval = 60 seconds to call this method repeatly
Update
Per your comments I guess what you want to update is the location info? Some references:
iOS Multitasking: Background Location
What can we use instead of nstimer?
Location Awareness Programming Guide
iOS App Programming Guide - Tracking the User’s Location
use NSTimer with 60 sec interval, write a method to get the text from the array and display it in the label.
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Xcode: Why is my timer count 2 seconds on every tick?
In my app I have a timer that should go from 12:00 to 0:00, but it counts 2 seconds on every tick like this:
11.58
11.56
11.54
11.52 and so on..
this is the code in the start button code:
tid.text=[NSString stringWithFormat:#"%d:%.2d",minuter,sekunder];
timer= [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(tidklick)
userInfo:nil
repeats:YES];
This is the method tidklick:
-(void) tidklick
{
tiden -= 1;
sekunder = tiden % 60;
minuter= (tiden - sekunder) / 60;
tid.text=[NSString stringWithFormat:#"%d:%.2d",minuter,sekunder];
}
This is the code in the beginning..
int tiden=720;
int sekunder;
int minuter;
and also when I hit a certain button, this should happen: i++;
but it seems like i gets added by 2 every time I hit the button....
What is wrong? :S Seems like something with Xcode and not my code?
EDIT: Now I noticed that when I hit the button that should stop the timer in the end(timer invalidate), it counts as normal... It counts one second at a time that is!
Thanks in advance!
For the second part of the question, when you hit your button: Have you made sure that your selector for the button isn't being called twice -- for instance when the button is pressed down and then again when it is lifted up.
When you say you 'hit the button', what is your button hitting code? There are several events that take place on a button "hit" (most notably button down and up events) which if you are not handling properly could increment i multiple times in a single 'hit'.
This could also be the reason the timer is doing down by two instead of one -- when you 'hit' the start button you are launching two timers instead of one, causing one second per timer to be decremented per second.
For better time counting try to use NSDate methods:
[NSDate date] for start value and [NSDate timeIntervalSinceDate:startTime] to get time shift from the start.
Timer firing interval is approximately equals to 1 second.
Setup
I'm currently developing a music app and I'm having problems with the progress bar slider.
self.musicPlayer is the [MPMusicPlayerController applicationMusicPlayer]
self.currentlyPlayingTotalDuration is an NSNumber
self.currentlyPlayingTimeSlider is a UISlider
Overview
The below code is executed when a new song is picked in the MPMusicPlayerController. In this method (not all of which is shown), I set my music player to play the picked song (working) and play it (working). Then I set the total duration of the song to the maximum value of the slider (working)
self.currentlyPlayingTotalDuration = [[NSNumber alloc] initWithFloat:(int)[NSValue valueWithPointer:[self.musicPlayer.nowPlayingItem valueForKey:MPMediaItemPropertyPlaybackDuration]]];
[self.currentlyPlayingTimeSlider setMaximumValue:self.currentlyPlayingTotalDuration.floatValue];
I've logged the values to see if the values are setting correctly (they are)
NSLog(#"Number:%#", [NSNumber numberWithFloat:(int)[NSValue valueWithPointer:[self.musicPlayer.nowPlayingItem valueForKey:MPMediaItemPropertyPlaybackDuration]]]);
NSLog(#"Max:%f", self.currentlyPlayingTimeSlider.maximumValue);
Log output is below, looking as it should
2011-08-24 13:38:25.004 App [1241:707] Number:1107392
2011-08-24 13:38:25.009 App [1241:707] Max:1400544.000000
And then I set my currentlyPlayingTimeSlider value to 0 to start (working)
self.currentlyPlayingTimeSlider.value = 0.0;
Next, I set my updateSliderTime method to call once per second to move the progress bar farther by one second (working)
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateSliderTime:) userInfo:nil repeats:YES];
Problems
The full method code is below for the updateSliderTime method, which is not working, even though it is being called every second
- (void)updateSliderTime:(NSTimer *)timer {
[self.currentlyPlayingTimeSlider setValue:[[NSNumber numberWithDouble:self.musicPlayer.currentPlaybackTime] floatValue]];
}
Also, the method I call for a valueChanged event that I've setup in Interface Builder is below. It also is not working
- (IBAction)sliderChanged:(id)sender {
[self.musicPlayer setCurrentPlaybackTime:[[NSNumber numberWithFloat:self.currentlyPlayingTimeSlider.value] doubleValue]];
}
Can anyone help me figure out what I'm doing wrong? It has to be something in these last two methods, as the first one calls fine. I do no other customization/messing with the slider anywhere else.
Did you check your IBAction is being called (perhaps with NSLog)? If not, make sure you set the delegate of the Slider.
Otherwise, check my answer to this question which is very similar.
Figured it out. Everything was actually working how it should except setting the maximum value for the slider. I converted it oddly. Instead of:
self.currentlyPlayingTotalDuration = [[NSNumber alloc] initWithFloat:(int)[NSValue valueWithPointer:[self.musicPlayer.nowPlayingItem valueForKey:MPMediaItemPropertyPlaybackDuration]]];
I should be using:
self.currentlyPlayingTotalDuration = [self.musicPlayer.nowPlayingItem valueForKey:MPMediaItemPropertyPlaybackDuration];
The value is already a number. Thanks to Mundi for motivating me to log the value. When I did, I realized it was already a float. Silly me :)
I'm trying to upload a few files to a server. The files are listed on the UItableview. My question is:
What should i do to display UIProgressView in each table cell and show the progress of each file being uploaded.
My current code is able to show the UIProgressView in each cell but when i try to upload, the progress bar did not move. The program is suppose to upload 1 file at a time which after the first file is completed, the second will start to upload. In response, when the first file is done, the progress bar of the first file will stop and the progress bar for the secong file will start to move. Hope this is clear. I really need some help on this and i can't find it on the web.Thanks in advance. Thanks
You will have to maintain the progress value of each cell in an array.
I guess you must be setting the progress value of UIProgressView object at cellForRowAtIndexPath method, so you need to call [self.tableView reloadData] whenever you get callback from you network code which is uploading file to server with current upload size...
Possible solution (could be optimized): (Sorry for the formatting, could not get it working)
Create UIProgressView for each cell in your tableView
Create a field in your view controller, where you will store number of bytes already uploaded (bytesAlreadyUploaded) - you should repeatidly receive such info from your uploader.
Create a field where you will store number of bytes to be uploaded for the current upload (bytesToUpload)
Create a field where you will assign pointer to the progress view currently used (progressViewCurrentlyUsed)
Create a method in which you will refresh your progress:
(void) refreshProgress {
progressViewCurrentlyUsed.progress =
bytesAlreadyUploaded /
(CGFloat)bytesToUpload;
}
Create a NSTimer, which will call this refreshProgress method several times a second:
refreshTimer = [NSTimer
timerWithTimeInterval:0.1 target:self
selector:#selector(refreshProgress)
userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop]
addTimer:refreshTimer
forMode:NSDefaultRunLoopMode];
When you change the file being uploaded, change progressViewCurrentlyUsed, bytesToUpload and zero bytesAlreadyUploaded
I am working on an application that needs a method to be called at a certain time (15 minutes past the hour to be exact). Is there a way to make this happen without consuming a ton of CPU and battery life? I've tried searching and just can't find an answer anywhere.
They made this really easy. Alloc an NSTimer and initialize it with the fire date, using:
-(id)initWithFireDate:(NSDate *)date
interval:(NSTimeInterval)seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats
then add it to the run loop using:
-(void)addTimer:(NSTimer *)aTimer forMode:(NSString *)mode
on the run loop, e.g. [NSRunLoop currentRunLoop]. Don't know if this will wake the device, or prevent it from sleeping.
edit some example code
// start in 5 minutes
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:300];
// fire every minute from then on
NSTimer *t = [[NSTimer alloc]
initWithFireDate:date
interval:60
target:self
selector:#selector(stuff:) // -(void)stuff:(NSTimer*)theTimer
userInfo:nil
repeats:YES
];
// make it work
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
and
-(void)stuff:(NSTimer*)theTimer
{
if ( done ) [theTimer invalidate];
}
If you need this to happen while your application is not running, have a look a UILocalNotification in iOS 4.0. It's unclear whether your application is running at the time that you need this notification or not, but in either case this class should get you pointed in the right direction.
http://developer.apple.com/iphone/library/documentation/iPhone/Reference/UILocalNotification_Class/Reference/Reference.html#//apple_ref/occ/cl/UILocalNotification
Okay, I have searched online and even looked in a couple of books for the answer because I can't understand the apple documentation for the NSTimer. I am trying to implement 2 timers on the same view that each have 3 buttons (START - STOP - RESET).
The first timer counts down from 2 minutes and then beeps.
The second timer counts up from 00:00 indefinitely.
I am assuming that all of the code will be written in the methods behind the 3 different buttons but I am completely lost trying to read the apple documentation. Any help would be greatly appreciated.
Basically what you want is an event that fires every 1 second, or possibly at 1/10th second intervals, and you'll update your UI when the timer ticks.
The following will create a timer, and add it to your run loop. Save the timer somewhere so you can kill it when needed.
- (NSTimer*)createTimer {
// create timer on run loop
return [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timerTicked:) userInfo:nil repeats:YES];
}
Now write a handler for the timer tick:
- (void)timerTicked:(NSTimer*)timer {
// decrement timer 1 … this is your UI, tick down and redraw
[myStopwatch tickDown];
[myStopwatch.view setNeedsDisplay];
// increment timer 2 … bump time and redraw in UI
…
}
If the user hits a button, you can reset the counts, or start or stop the ticking. To end a timer, send an invalidate message:
- (void)actionStop:(id)sender {
// stop the timer
[myTimer invalidate];
}
Hope this helps you out.
I would follow Jonathan's approach except you should use an NSDate as your reference for updating the UI. Meaning instead of updating the tick based on the NSTimer, when the NSTimer fires, you take the difference between NSDate for now and your reference date.
The reason for this is that the NSTimer has a resolution of 50-100 ms which means your timer can become pretty inaccurate after a few minutes if there's a lot going on to slow down the device. Using NSDate as a reference point will ensure that the only lag between the actual time and the time displayed is in the calculation of that difference and the rendering of the display.