Show timer in an app? [closed] - ios

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm using Xcode with Objective C language. I wanted to know if there is any method to show a timer or a counter which shows as to how long the application is being running. It simple increments the counter to seconds, minutes however long the app is running. Any help would be appreciated.
Thank You

Create one UILable in your RootViewController or UIWindow and then update it frequently with following way.
create one Variable in .h file.
#property (nonatomic) int seconds;
put following code in ViewDidLoad method of your RootViewController
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateLabel) userInfo:nil repeats:YES];
[timer fire];
Create following Function to update UILabel.
- (void) updateLabel {
self.seconds = self.seconds + 1;
NSLog(#"You can show time in minutes, hours and day also after doing some calculation as per your need");
[self.lblDemo setText:[NSString stringWithFormat:#"%d seconds",self.seconds]];
}

Related

Objective-C: Flip the pages through different time intervals [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 6 years ago.
Improve this question
There are 10 pages that I want to turn at different time intervals. I need to create 10 timers for flip? Or can I make an array intervals and to insert them to the timer? Сan I do it in a simpler way?
There are a lot of ways to do this. Here's one:
This is possibly a good solution if your intervals are irregular and far apart. If they are more evenly spaced (e.g. first is two seconds, next is four seconds) then you could simplify this design. But, I'm assuming that you just want to be able to pass in an array of intervals and then let the code take care of it all.
For this implementation, we're going to need an instance variable to hold an array of timers. Use a property if you prefer them to instance variables.
#implementation ViewController {
NSArray *_multipleTimerInstances;
}
Then some code to handle the timings.
- (void)multipleTimers:(NSArray *)durations {
// Get rid of any timers that have already been created.
[self mulitpleTimerStopAll];
NSMutableArray *newTimers = [NSMutableArray new];
// Create the new timers.
[durations enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
// Each element of the durations array specifies the flip interval in seconds.
double duration = [(NSNumber *)obj doubleValue];
// Schedule it.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:duration
target:self
selector:#selector(multipleTimersFlip:)
userInfo:[NSNumber numberWithInteger:idx]
repeats:YES];
// Keep a reference to the new timer so we can invalidate it later, if we want.
[newTimers addObject:timer];
}];
// We now have a new list of timers.
_multipleTimerInstances = [newTimers copy];
}
- (void)multipleTimersFlip:(NSTimer *)timer {
NSInteger index = [timer.userInfo integerValue];
// The integer index corresponds to the index of the timer in the array passed
// to the multipleTimers method.
NSLog(#"Flip page for timer with index: %ld", (long)index);
}
- (void)mulitpleTimerStopAll {
// Get rid of any timers that have already been created.
for (NSTimer *timer in _multipleTimerInstances) [timer invalidate];
// And nil out the array, they're gone.
_multipleTimerInstances = nil;
}
Then you can invoke the timers like this:
[self multipleTimers:#[ #5.0, #10.0, #7.5 ]];
That's going to call back the multipleTimersFlip method every 5, 7.5, and 10 seconds.
Remember to call multipleTimersStopAll to stop all this going on when you don't need it.

How to load interstitial ads when Navigation Back Button Pressed and Some Click Event? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am new to iOS development. I am adding an interstitial ads when ViewDidLoad but I want to show interstitial ads when an user clicks ten times in my application, is that possible? If it is possible then please help me finding a solution. My Application contains HMSegmentedControll and it has ten different UITableView. And I also want to display these ads when NavigationBar back button is pressed. Could anyone help me with this?
It is Possible like as SharedPreference in Android
Make One Global Variable NSObject like as
GlobalVariable.h File
#property (assign) int touchCount;
+ (TouchCount *)getInstance;
#end
and GlobalVariable.m File
#synthesize touchCount;
static TouchCount *instance = nil;
+(TouchCount *)getInstance
{
#synchronized(self)
{
if(instance==nil)
{
instance= [TouchCount new];
}
if (instance.touchCount ==10)
{
instance.touchCount=0;
instance= [TouchCount new];
}
}
return instance;
}
And Use this Instance when You Want to Touch Count import GLobalVariable.hlike as
TouchCount *obj=[TouchCount getInstance];
Whell u can add some global value than counts "back taps"
in GlobalVariables.h file something like this:
extern int PRJ_back_touches_count;
.m:
int PRJ_back_touches_count;
Than e.g. in viewWillDisappear method PRJ_back_touches_count++
On viewDidAppear u can handle the PRJ_back_touches_count actual value

Increment NSDate for use in for loop [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 9 years ago.
Improve this question
I am looking for a way to write a for loop that iterates over an NSDate. Each loop should increment the NSDate by 10 seconds.
I want to have 2 timestamps. Say timestamp A is Midnight Monday and timestamp B is Midnight Tuesday.
What I then want is some code to say for A to B incrementing at 10 second intervals between the two points in time, use the timestamp at current position, and the timestamp at the last position, so I can run a query based on the intervals.
Would someone be so good as to show me how I would do this?
Many thanks
A for loop needs three parts, an initialisation, a compare, and an increment. It could look like this:
for (NSDate *date = startDate; // initialisation
[date compare:endDate] == NSOrderedAscending; // compare
date = [date dateByAddingTimeInterval:10]) // increment
{
// do something with date here, eg:
NSDate *rangeStart = date;
NSDate *rangeEnd = [date dateByAddingTimeInterval:10];
[runQuery begin:rangeStart end:rangeEnd];
}
You might prefer to refactor to use a while loop so that the dateByAddingTimeInterval doesn't need to be repeated.
This is the same structure as a normal for loop:
for (int i = 0; // initialisation
i < 10; // compare
i++) // increment
{
// do something with i here
}
It sounds like you may want to look into NSTimer's timerWithTimeInterval. The interface looks like this:
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
and then you can start one ten seconds later using:
initWithFireDate:interval:target:selector:userInfo:repeats:
You can sign up for a call that is sent every seconds as shown below:
// SomeClass.m
#import "SomeClass.h"
#interface ()
#property (nonatomic, strong) NSTimer timer1;
#property (nonatomic, strong) NSTimer timer2;
#end
#implementation SomeClass
- (id)init
{
self = [super init];
if (self) {
NSDate* date = [[NSDate date] dateByAddingTimeInterval:10];
self.timer1 = [NSTimer timerWithTimeInterval:10 target:self selector:#selector(timerFireMethod:) userInfo:nil repeats:YES];
self.timer2 = [[NSTimer alloc] initWithFireDate:date interval:10 target:self selector:#selector(timerFireMethod:) userInfo:nil repeats:YES];
}
return self;
}
- (void)timerFireMethod:(NSTimer *)timer
{
if (timer == self.timer1) {
NSLog(#"timer1 fired");
}
}
#end

Counter implementation using NsTimer in objective-c

I have surfed on a bunch of resources from the internet but still couldn't get any idea of what I'm trying to implement.
I would like to record user preferences by detecting how much time they have stayed in each information pages.
In order to make this question simpler, that says I have a entrance page with 5 different theme pages which represent different information.
I would like to know which page is the page that user most interesting.
What I wish to do is to put a counter in each theme pages and calculate how much time they stay in that page (the counter should be able to pause for reentrance), and then when I press a button on the entrance page, an alert will tell me which page is the page that user spent most of time on it.
I hope this make sense!
Does anyone have any experience on this? I would be most appreciative if anyone can provide some codes and examples for me.
ViewController A:
- (void)viewDidLoad {
[super viewDidLoad];
//create iVar of NSInteger *seconds
seconds = 0;
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(increaseTimeCount) userInfo:nil repeats:YES];
[timer fire];
}
- (void)increaseTimeCount {
seconds++;
}
- (void)dealloc {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// you can add to array too , if you want and get average of all values later
[defaults setInteger:seconds forKey: NSStringFromClass(self)];
}
now in Entrance View ..
get the time as
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger *secondsInView = [defaults integerForKey:NSStringFromClass(View1ClassName)];
Firstly I'd like to draw your attention to the Cocoa/CF documentation (which is always a great first port of call). The Apple docs have a section at the top of each reference article called "Companion Guides", which lists guides for the topic being documented (if any exist). For example, with NSTimer, the documentation lists two companion guides:
Timer Programming Topics for Cocoa
Threading Programming Guide
For your situation, the Timer Programming Topics article is likely to be the most useful, whilst threading topics are related but not the most directly related to the class being documented. If you take a look at the Timer Programming Topics article, it's divided into two parts:
Timers
Using Timers
For articles that take this format, there is often an overview of the class and what it's used for, and then some sample code on how to use it, in this case in the "Using Timers" section. There are sections on "Creating and Scheduling a Timer", "Stopping a Timer" and "Memory Management".There are a couple of ways of using a timer. From the article, creating a scheduled, non-repeating timer can be done something like this:
1) scheduled timer & using selector
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:#selector(onTick:)
userInfo: nil repeats:NO];
if you set repeats to NO, the timer will wait 2 seconds before
running the selector and after that it will stop;
if repeat: YES, the timer will start immediatelly and will repeat
calling the selector every 2 seconds;
to stop the timer you call the timer's -invalidate method: [t
invalidate]; As a side note, instead of using a timer that doesn't
repeat and calls the selector after a specified interval, you could
use a simple statement like this:
[self performSelector:#selector(onTick:) withObject:nil afterDelay:2.0];
this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;
2) self-scheduled timer
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
interval: 1
target: self
selector:#selector(onTick:)
userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
this will create a timer that will start itself on a custom date
specified by you (in this case, after a minute), and repeats itself
every one second
3) unscheduled timer & using invocation
NSMethodSignature *sgn = [self methodSignatureForSelector:#selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:#selector(onTick:)];
NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:YES];
and after that, you start the timer manually whenever you need like this:
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];
And as a note, onTick: method looks like this:
-(void)onTick:(NSTimer *)timer {
//do smth
}
Try this simple method:
- (void)viewDidLoad
{
[super viewDidLoad];
count = 0; // Declare int * count as global variable;
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(timerAction) userInfo:nil repeats:YES];
}
- (void)timerAction
{
[self custom_method:count++]
}
Might I suggest a different route. If you take the time since reference date, when the user enters the page:
NSTimeINterval time = [NSDate timeIntervalSinceReferenceDate]
then do the same when they leave the page and compare them.
timeOnPage = time - time2;
This is much more efficient than firing a timer on another thread unnecessary.
You do not need to use NSTimers for this at all.
Store the date/time when the user starts viewing, and calculate the time difference when they stop viewing using simple time arithmetic.
Exactly As Dave Wood says You should use date and time for starting and ending viewing that screen and calculate the difference and then save it to any integer variable.Using NSTimer will make the performance effect in your app and make the compiler busy while incrementing the count.

Randomly move the uibutton some 8 static position using timer in ios [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have doubt in to moving uibutton randomly from one position to another position, the position's are static. There are totall eight positions. Using timer i will call dis method.
save those 8 positions in 8 CGRects.
then generate a random number between 1 and 8 using int r = arc4random() % 8;.
using switch statement set the CGRect of the button depending on r.
in your .h file add this:
#property (nonatomic, strong) NSTimer *timer;
#property (nonatomic, strong) NSMutableArray *framesArray;
in your .m file add these:
in your viewDidLoad method:
_timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(changeButtonPositions) userInfo:nil repeats:YES];
_framesArray = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithCGRect:CGRectMake(x_1, y_1, w_1, h_1)],[NSValue valueWithCGRect:CGRectMake(x_2, y_2, w_2, h_2)],[NSValue valueWithCGRect:CGRectMake(x_3, y_3, w_3, h_3)],[NSValue valueWithCGRect:CGRectMake(x_4, y_4, w_4, h_4)],[NSValue valueWithCGRect:CGRectMake(x_5, y_5, w_5, h_5)],[NSValue valueWithCGRect:CGRectMake(x_6, y_6, w_6, h_6)],[NSValue valueWithCGRect:CGRectMake(x_7, y_7, w_7, h_7)],[NSValue valueWithCGRect:CGRectMake(x_8, y_8, w_8, h_8)], nil];
When you want to start animate the changingButton, do it like this:
[_timer fire];
and add this method:
- (void) changeButtonPositions{
int number = arc4random() % 8;
changingButton.frame = [[_framesArray objectAtIndex:number] CGRectValue];
}
when you want to finish animating, do
[_timer invalidate];

Resources