furoyo
furoyo

Reputation: 21

Total played time of game in Xcode?

I am creating this game on Xcode and I want to keep track of total played time in seconds as the score. But how do I keep the total played time in a variable? Thanks!

Upvotes: 0

Views: 166

Answers (2)

Alex
Alex

Reputation: 1245

The most easy way is to save timestamp of game start using Date() and on game finish call the code like this:

let seconds = Date().timeIntervalSinse(startDate)

Constant "seconds" will contain number of seconds in Double format. If you want to check how much time the user spent in the app, the best place for startDate saving is applicationDidBecomeActive(_ application: UIApplication) is of your app delegate and for finish date - applicationWillResignActive(_ application: UIApplication)

Upvotes: 3

Malik
Malik

Reputation: 3802

You can use NSTimer for this purpose. Create a class variable totalTime

var totalTime = 0

Create a timer

let timer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true)

Then you can define your tick method as

func tick() {
    totalTime += 1
}

Don't forget to invalidate your timer when you are finished

Upvotes: 0

Related Questions