Reputation: 12123
Can I find out how long a user is sat on a UIViewController for?
Upvotes: 0
Views: 113
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