Popeye
Popeye

Reputation: 12123

Found how long user is on UIView for

Can I find out how long a user is sat on a UIViewController for?

Upvotes: 0

Views: 113

Answers (1)

hwaxxer
hwaxxer

Reputation: 3383

Set an NSDate in -viewDidAppear: and call [[NSDate date] timeIntervalSinceDate:yourDate] in -viewDidDisappear:. You'll get the number of seconds spent in the UIViewController.

If don't want you track time when the application is not active, add the UIViewController as an observer for the UIApplicationDidBecomeActiveNotification & UIApplicationWillResignActiveNotification, calling the -didBecomeActive and -didResignActive methods respectively.

- (void)didBecomeActive 
{
    self.startDate = [NSDate date];
}
- (void)didResignActive
{
    timeSpent += [[NSDate date] timeIntervalSinceDate:startDate]
}
- (void)viewWillAppear:(BOOL)animated
{
    [self didBecomeActive];
    [super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self didResignActive];
    [super viewWillDisappear:animated];
}    

Update: added code to handle if app becomes inactive

Upvotes: 3

Related Questions