Creating a simple timer in WatchOS with Swift 4 - ios

Seemingly simple but I'm struggling...the code below crashes on the line setting the date of the workoutTimer. Also my WKInterfaceTimer isn't hooked up to an IBOutlet, does it need to be? I wanted to use it just for purposes of the time.
class InterfaceController {
var workoutTimer: WKInterfaceTimer!
var workoutStartTime: NSDate? = nil
func startWorkOutTimer() {
self.startWorkout()
if let test = self.workoutSecondsElapsed() {
print("timer seconds = \(test)")
}
}
func startWorkout() {
// To count up use 0.0 or less, otherwise the timer counts down.
workoutTimer.setDate(NSDate(timeIntervalSinceNow: 0.0) as Date)
workoutTimer.start()
self.workoutStartTime = NSDate()
}
func stopWorkout() {
workoutTimer.stop()
}
func workoutSecondsElapsed() -> TimeInterval? {
// If the timer hasn't been started then return nil
guard let startTime = self.workoutStartTime else {
return nil
}
// Time intervals from past dates are negative, so
// multiply by -1 to get the elapsed time.
return -1.0 * (self.workoutStartTime?.timeIntervalSinceNow)!
}
}

From Apple doc:
Do not subclass or create instances of this class yourself. Instead, define outlets in your interface controller class and connect them to the corresponding objects in your storyboard file.
Your app probably is crashing because your timer is nil, but for what you need you can use Timer class instead of WKInterfaceTimer.

Related

Timer and dependancy injection

I've just started with Swift and using MVVM with dependency injection.
In my ViewModel I have Timer that handles refreshing the data. I've simplified the code a little for clarity.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let viewModel = ViewModel()
}
}
class ViewModel: NSObject {
private var timer: Timer?
override init() {
super.init()
setUpTimer()
}
func setUpTimer() {
timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true){_ in
self.refreshData()
}
}
func refreshData() {
//refresh data
print("refresh data")
}
}
I want to use dependency injection to pass the Timer into the ViewModel so that I can control the timer when doing unit tests and make it call immediately.
So passing the Timer is pretty simple. How can I pass a Timer in to ViewModel that has the ability to call the refreshData() belonging to ViewModel. Is there a trick in Swift that allows this?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true){_ in
// call refreshData() from the class ViewModel
}
var viewModel = ViewModel(myTimer:timer)
}
}
class ViewModel: NSObject {
private var timer: Timer?
init(myTimer:Timer) {
super.init()
//setUpTimer()
timer = myTimer
}
func refreshData() {
//refresh data
print("refresh data")
}
}
I thought it might be possible using the scheduelTimer that takes a selector instead of a block but that would require using a #objc before the func refreshData() which seems clunky since I am using an Objective C feature in Swift.
Is there a nice way to achieve this?
Many Thanks,
Code
Conceptually, you want to decouple the implementation. So instead of having to pass Timer to the view model, you pass some other "control" object, which guarantees to perform the operation (of calling back after a delay)
If that doesn't shout protocol, I don't know what does...
typealias Ticker = () -> Void
protocol Refresher {
var isRunning: Bool { get }
func register(_ ticker: #escaping Ticker)
func start();
func stop();
}
So, pretty basic concept. It can start, stop and an observer can register itself to it and be notified when a "tick" occurs. The observer doesn't care "how" it works, so long as it guarantees to perform the specified operation.
A Timer based implementation then might look something like...
class TimerRefresher: Refresher {
private var timer: Timer? = nil
private var ticker: Ticker? = nil
var isRunning: Bool = false
func register(_ ticker: #escaping Ticker) {
self.ticker = ticker
guard timer == nil else {
return
}
}
func start() {
guard ticker != nil else {
return
}
stop()
isRunning = true
timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true, block: { (timer) in
self.tick()
})
}
func stop() {
guard let timer = timer else {
return
}
isRunning = false
timer.invalidate()
self.timer = nil
}
private func tick() {
guard let ticker = ticker else {
stop()
return
}
ticker()
}
}
This provides you the entry point for mocking the dependency injection, by replacing the implementation of the Refresher with one you can control manually (or use a different "delaying" action, depending on your needs)
This is just a conceptual example, your implementation/needs may differ and lead you to a slightly different design, but the idea remains the same, decouple the physical implementation in some way.
An alternative would require you to rethink your design, and instead of the view model performing it's own refresh, the view/controller would take over that responsibility instead. Since that's a significant design decision, you're really only the person who can make that decision, but it's another idea
If I understand you correctly, you want the model to refresh every 30 seconds when running in the app, but faster for test. If so, don't inject the Timer. Inject the refresh frequency.
class ViewModel: NSObject {
// We need something to observe and confirm that the data is fresh
#objc dynamic var lastRefreshed: Date?
private var timer: Timer!
// The default frequency is 30 seconds but users can adjust that
// The unit test uses it to inject dependency
init(refreshFrequency: TimeInterval = 30) {
super.init()
timer = Timer.scheduledTimer(timeInterval: refreshFrequency, target: self, selector: #selector(refreshData), userInfo: nil, repeats: true)
}
#objc func refreshData() {
lastRefreshed = Date()
print("refreshed on: \(lastRefreshed!)")
}
}
And your unit test:
func testModel() {
let startTime = Date()
let model = ViewModel(refreshFrequency: 5)
// Test first refresh: must be within 5 - 6 seconds from startTime
keyValueObservingExpectation(for: model, keyPath: #keyPath(ViewModel.lastRefreshed)) { (_, _) -> Bool in
if let duration = model.lastRefreshed?.timeIntervalSince(startTime), 5...6 ~= duration {
return true
} else {
return false
}
}
// Test second refresh: must be within 10 - 12 seconds from startTime
keyValueObservingExpectation(for: model, keyPath: #keyPath(ViewModel.lastRefreshed)) { (_, _) -> Bool in
if let duration = model.lastRefreshed?.timeIntervalSince(startTime), 10...12 ~= duration {
return true
} else {
return false
}
}
// Wait 12 seconds for both expectations to be fulfilled
waitForExpectations(timeout: 12, handler: nil)
}
Timer is not exact: it does not fire exactly every 5 seconds like you asked. Apple say Timer is accurate to about 50 - 100ms. Hence we cannot expect that the first refresh will happen 5 seconds from now. We must allow for some tolerances. The further out you go, the bigger this tolerance have to become.

Computer AI turns in a UIViewController

In a swift game using UIKit I am writing, a human player will interact with UIKit UIButtons, GUI elements to take actions.
In the game, the player will play against AI players.
But here's the thing; the human player presses buttons and interacts and the AI player does not.
Given a simple UIViewController;
class SampleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func buyBtnPressed(_ sender: UIButton) {
print ("pressed")
}
}
So what I'm trying to ascertain is, how does the AI player itself take actions and handling turns within the context of the current view controller?
I believe the best way to do this is that there should be a loop that will wait until all players have completed their respective turns.
But where does this loop go? In the view did load?
If so, won't it eat up memory, or potentially lead (if not careful) to an endless loop?
I'm finding it hard to ascertain how an AI player can take actions within the given context of a UIViewController considering GUI elements are for human interaction.
I don't mean the AI should be animating pressing buttons or interacting with the screen, I mean; I have a UIViewController, it has a view did load; what is the strategy of implementing AI turns and whether or not this should be be achieved in a "game loop" in the View did load or can this be achieved in another way?
My question is; given the context of a UIViewController; how can I code the handling of an AI player taking turns and can this be achieved with a loop or another strategy?
Many thanks
edit: Code is now added
I have written out a turn base manager using Swift playgrounds, and 2 examples one using a UIViewController and another is a loop.
code now follows;
import Foundation
import GameplayKit
class Player {
var name: String
public private(set) var isAI: Bool = false
public private(set) var turnOrder: Int = 0
init(name: String, isAI: Bool?) {
self.name = name
if let hasAI = isAI {
self.isAI = hasAI
}
}
func setTurnOrderIndex(number: Int) {
self.turnOrder = number
}
}
let p1 = Player.init(name: "Bob", isAI: false)
let p2 = Player.init(name: "Alex", isAI: true)
protocol TurnOrderManagerDelegate: NSObjectProtocol {
func turnOrderWasSet()
}
protocol TurnDelegate: class {
func turnIsCompleted()
}
class Turn: NSObject {
weak var player: Player?
weak var delegate: TurnDelegate?
public private(set) var completed: Bool = false {
didSet {
delegate?.turnIsCompleted()
}
}
init(player:Player, delegate: TurnDelegate) {
self.player = player
self.delegate = delegate
}
func setAsComplete() {
self.completed = true
}
}
class TurnOrderManager: NSObject, TurnOrderManagerDelegate, TurnDelegate {
static var instance = TurnOrderManager()
public private(set) var turnOrderIndex: Int = 0
public private(set) var turnOrder: [Turn] = [Turn]() {
didSet {
self.turnOrderWasSet()
}
}
var playerOnTurn: Player? {
let turnObj = self.turnOrder[turnOrderIndex]
return (turnObj.player)
}
var allTurnsCompleted: Bool {
let filtered = turnOrder.filter { (turnObj:Turn) -> Bool in
return (turnObj.completed)
}.count
return (filtered == turnOrder.count)
}
func setTurnOrder(players:[Player]) {
if (self.turnOrder.count == 0) {
for playerObj in players {
let turnObj = Turn.init(player: playerObj, delegate: self)
self.turnOrder.append(turnObj)
}
}
}
func turnOrderWasSet() {
for (index, turnObj) in self.turnOrder.enumerated() {
turnObj.player?.setTurnOrderIndex(number: index)
}
}
func next() {
if (turnOrderIndex < (self.turnOrder.count - 1)) {
turnOrderIndex += 1
}
else {
turnOrderIndex = 0
}
}
internal func turnIsCompleted() {
print (" - turnIsCompleted")
TurnOrderManager.instance.next()
}
}
class GameModel {
var turnOrderManager: TurnOrderManager
init() {
self.turnOrderManager = TurnOrderManager.instance
self.turnOrderManager.setTurnOrder(players:[p1,p2])
}
// other game model stuff [...]
}
class Phase1State : GKState {
var gameModel: GameModel!
init(gameModel:GameModel) {
super.init()
self.gameModel = gameModel
}
override func isValidNextState(_ stateClass: AnyClass) -> Bool
{
return false
}
override func didEnter(from previousState: GKState?) {
}
override func willExit(to nextState: GKState) {
}
// MARK: - Action
func buy() {
let index = self.gameModel.turnOrderManager.turnOrderIndex
let turn = self.gameModel.turnOrderManager.turnOrder[index]
turn.setAsComplete()
}
}
class SomeViewController: UIViewController
{
var gameModel: GameModel?
weak var gamePhase: Phase1State?
var isPhaseComplete: Bool {
return self.gameModel?.turnOrderManager.allTurnsCompleted ?? false
}
override func viewDidLoad() {
super.viewDidLoad()
self.gameModel = GameModel.init()
self.gamePhase = Phase1State.init(gameModel: self.gameModel!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func buyButtonPressed() {
self.gamePhase?.buy()
self.finishTurn()
}
func finishTurn() {
guard let turnIndex = self.gameModel?.turnOrderManager.turnOrderIndex else {
return
}
guard let turn = self.gameModel?.turnOrderManager.turnOrder[turnIndex] else {
return
}
turn.setAsComplete()
if (self.isPhaseComplete)
{
print ("All turns are completed")
}
else {
//self.gameModel?.turnOrderManager.next()
self.gamePhase?.buy()
guard let playerOnTurn = self.gameModel?.turnOrderManager.playerOnTurn else {
print ("No player is on turn")
return
}
print ("\(playerOnTurn.name) is on turn")
if (playerOnTurn.isAI)
{
self.gamePhase?.buy()
self.finishTurn()
}
}
}
}
// EXAMPLE 1 -- first attempt ...
let vc = SomeViewController()
vc.viewDidLoad()
vc.buyButtonPressed()
// EXAMPLE 2 -- another attempt ....
let gameModel: GameModel = GameModel.init()
let gamePhase = Phase1State.init(gameModel: gameModel)
// player then takes an action
while (gameModel.turnOrderManager.allTurnsCompleted == false)
{
let turnIndex = gameModel.turnOrderManager.turnOrderIndex
let turnObj = gameModel.turnOrderManager.turnOrder[turnIndex]
guard let playerOnTurn = turnObj.player else {
break
}
print ("Player \(playerOnTurn.name) is on turn")
gamePhase.buy()
}
print ("All turns are completed, advance to next phase")
The issue is;
On the finishTurn, it only seems to work if it relies on the first player in the index is a human player. If its not, I have no idea how to make it fire the buy action.
On the second example, I use a loop; but I'm concerned using a loop could end up just looping forever.
My query is therefore clarifyed, how can I ensure my view controller will fire actions for AI players when they don't press buttons and loop through each player and execute their respective turn.
Many thanks
Further edit:
I do not know if I should have the while (gameModel.turnOrderManager.allTurnsCompleted == false) loop inside my viewDidLoad() to act like a game loop.
There is no need to specifically use Sprite Kit for this. SpriteKit would be more to do with how the UI is made rather than how the logic of the game works.
However, I would recommend looking at GameplayKit. It's a framework that contains lots of built in game logic tools. Specifically you want something like the GKDecisionTree. There are a few WWDC videos about it too. GameplayKit can be used with SpriteKit, UIKit, SSceneKit or any other game engine that you decide to use (or not).
Also, the question you're asking is a very general question about game development. Having the computer "decide" to do something is quite a complex subject.
I'd also suggest having a quick watch of this video from AI & Games and other videos from that channel.
It'll give you an idea of how to approach your problem.
Session 609 and 608 from WWDC 2015 and 2016 are prob good :D
Regarding updating the AI.
Your AI should be event driven. You have the concept of "turns" and "players". There is a point in the game at which it becomes a "player's" "turn". (Even at the very beginning of the game it is either Player 1 or Player 2's turn.
At this time there are two possibilities. Either the player is an AI, or the player is a person.
As soon as this happens there should be some sort of trigger (like a function call or something) that tells the player its turn has started.
If that player is the AI then you need to start some sort of calculation (maybe with a built in delay to make it realistic) so that it decides what to do.
Look, I'm not sure on what kind of game you're making, buy you should probably learn SpriteKit, specially SKActions. With that, you can easily control the flow of events from your game.
With that said, how is your AI implementation? Based on your code, I would begin with something like this:
class AI {
enum Decision {
case doSomething
case doAnotherThing
case dontDoAnything
}
public func decide() -> Decision {
// Decide which action the AI will take...
return .doSomething // This return is just a example!
}
public func act(on : Decision) {
// Do whatever the AI needs based on a decision...
}
}
Then, in your ViewController:
class SampleViewController: UIViewController {
var ai = AI()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func buyBtnPressed(_ sender: UIButton) {
print ("pressed")
ai.act(on: ai.decide())
}
}
I hope that helps!

Singleton SharedInstance Function Called Twice

All singleton functions are twice calls.
The "Prova" function, and the selector of the timer are twice calls.
class Timer {
static let sharedInstanceTimer = Timer()
var TimerCounter : NSTimer = NSTimer()
var Counter : Int = Int()
var TimerGameOver : Int = Int()
var TimerBonusMultipleCircle : Int = Int()
var TimerBonusBigCircle : Int = Int()
var TimerCounterInterval : NSTimeInterval = 1
init()
{
self.Counter = 60
self.TimerGameOver = 10
self.TimerBonusMultipleCircle = 5
self.TimerBonusBigCircle = 5
self.TimerCounterInterval = 1
}
func StartTimerCounter()
{
self.TimerCounter = NSTimer.scheduledTimerWithTimeInterval(self.TimerCounterInterval, target: Game.sharedInstanceGame, selector: #selector(Game.sharedInstanceGame.UpdateAllCounter), userInfo: nil, repeats: true)
}
func StopTimerCounter()
{
self.TimerCounter.invalidate()
}
}
And... In another file I call StartTimerCounter()
import UIKit
class FirstViewController: UIViewController {
static let sharedInstanceFirstViewController = FirstViewController()
override func viewDidLoad() {
super.viewDidLoad()
let backButton = UIBarButtonItem(title: "00:00:60", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
backButton.tintColor = UIColor.whiteColor()
navigationItem.leftBarButtonItem = backButton
Circle.sharedInstanceCircle.CreateCircle()
view.layer.addSublayer(Circle.sharedInstanceCircle.PrincipalCircle)
Game.sharedInstanceGame.Play()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func ReturnToMenu()
{
navigationController?.popViewControllerAnimated(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Leaving aside the various errors that I corrected as suggested below I have tried several solutions but I can not find the solution to this problem.
A couple of thoughts:
Your sharedInstanceTimer is instantiating Timer (which is, itself, a NSTimer). It should not subclass NSTimer.
You then initialize TimerCounter to a second timer which you never use.
The above will instantiate two timers. You then have StartTimerCounter that instantiates another NSTimer every time you call it. Assuming you want only one timer, you should should have StartTimerCounter invalidate any prior timer before starting a new one.
I'd call this class TimerManager, or something like that, to avoid clashes with Swift 3 type, Timer.
Method names should start with lowercase letters, as should properties. In the spirit of the Swift 3 API guidelines, you might want to shorten the method names, too.
Also, if you're going to define a singleton, I'd declare a private init() initializer, to prevent other classes from accidentally ever instantiating another TimerManager object.
So, that yields something like:
class TimerManager {
static let shared = TimerManager()
private var timer: NSTimer? // this certainly should be private
// whether you make these private or not, or constants vs properties, is up to you
private var tounter : Int = 60
private var timerGameOver : Int = 10
private var timerBonusMultipleCircle : Int = 5
private var timerBonusBigCircle : Int = 5
private var timerCounterInterval : NSTimeInterval = 1
// make sure no one else accidentally instantiates another TimerManager
private init() {
}
/// Start timer.
func startTimer() {
stopTimer() // cancel prior timer, if any
timer = NSTimer.scheduledTimerWithTimeInterval(timerCounterInterval, target: Game.sharedInstanceGame, selector: #selector(Game.sharedInstanceGame.updateAllCounter), userInfo: nil, repeats: true)
Game.sharedInstanceGame.prova()
}
/// Stop timer.
func stopTimer() {
timer?.invalidate()
timer = nil
}
}
An unrelated, deeper observation here: I'd suggest that you keep the timer object loosely coupled with respect to the Game object. So, I'd excise all "game" related stuff from this class:
class TimerManager {
static let shared = TimerManager()
private var timer: NSTimer? // this certainly should be private
private var timerHandler: (() -> ())?
// whether you make these private or not, or constants vs properties, is up to you
private var timerCounterInterval: NSTimeInterval = 1
// make sure no one else accidentally instantiates another TimerManager
private init() {
}
/// Start timer.
///
/// - parameter timerHandler: The closure that will be called once per second.
func startTimer(timerHandler: () -> ()) {
stopTimer() // cancel prior timer, if any
self.timerHandler = timerHandler
timer = NSTimer.scheduledTimerWithTimeInterval(timerCounterInterval, target: self, selector: #selector(handleTimer(_:)), userInfo: nil, repeats: true)
}
#objc func handleTimer(timer: NSTimer) {
timerHandler?()
}
/// Stop timer.
func stopTimer() {
timer?.invalidate()
timerHandler = nil
timer = nil
}
}
Then, when the Game object wants to start a timer, it might do:
TimerManager.shared.startTimer {
self.updateAllCounter()
}
prova()
Now, perhaps you simplified your timer object for the purpose of this question and perhaps there's more that's needed in this TimerManager object (as suggested by all these other properties that aren't otherwise referenced in your code snippet), but hopefully this illustrates the basic idea: The TimerManager shouldn't be involved in the business of calling any specific Game methods or the like. It should simply provide a mechanism by which the caller can simply supply a block of code that the timer should periodically invoke.

NSTimeInterval as a countdown timer, applying it as a seperate reusable class

EDIT: I'm an idiot. I was trying to put the variable into NSTimer() and not NSTimeInterval for whatever silly reason. I guess my question is how can I wrap this all up in a separate class?
Ideally, I'd like all this wrapped up in a separate class (CountdownTimer), so I can create new instance of a timer but still retain all the functionality that NSTimer includes such as the ability to check timer.isValid. Psuedocode would look something like:
var timer = CountdownTimer(countDownFrom: 300)
timer.start()
timer.isValid()
My UIViewController class (not in viewDidLoad):
var totalCountDownTimeInterval = NSTimeInterval(480.0)
var startTime = NSDate()
var timer = NSTimer()
var isRunning = false
func updateTime() {
var elapsedTime : NSTimeInterval = NSDate().timeIntervalSinceDate(startTime)
var remainingTime : NSTimeInterval = totalCountDownTimeInterval - elapsedTime
if remainingTime <= 0.0 {
timer.invalidate()
}
let minutes = UInt8(remainingTime / 60.0)
remainingTime = remainingTime - (NSTimeInterval(minutes) * 60)
let seconds = UInt8(remainingTime)
println("The time is \(minutes) and \(seconds)")
}
#IBOutlet weak var TimerCount: UILabel!
#IBAction func StartButton(sender: AnyObject) {
if !timer.valid {
startTime = NSDate()
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.10, target: self, selector: aSelector, userInfo: nil, repeats: true)
}
}
#IBAction func StopButton(sender: AnyObject) {
timer.invalidate()
}
#IBAction func ResetButton(sender: AnyObject) {
timer.invalidate()
TimerCount.text = "00:00"
}
Make sure that you're actually passing in a double. I like to explicitly state the type of my variables when I declare them; it helps to avoid problems just like this.
You're most likely declaring doubleValue like this:
let doubleValue = 480
instead of like this:
let doubleValue = 480.0
or like this:
let doubleValue: Double = 480
If you've declared your variable correctly, this should work:
let timeInterval = NSTimeInterval(doubleValue)
If you are going to let the compiler infer the variable's type, just make sure that whatever's on the right side of your assignment operator evaluates to the type you're looking for. 480 evaluates to Int(480) while 480.0 evaluates to Double(480).
EDIT: Here's the answer to your second question: How can I wrap this [timer functionality] up in a separate class?
It's actually really simple. Assuming that all you want to do with the class is to be able to start it and check if it's still valid, here's how I would go about doing this:
class CountdownTimer
{
var time: NSTimeInterval
private var startTime: NSDate?
init(countDownFrom timeInSeconds: Int)
{
time = NSTimeInterval(timeInSeconds)
}
func start()
{
startTime = NSDate()
}
func isValid() -> Bool
{
if (startTime != nil)
{
let timePassed: NSTimeInterval = -(startTime!.timeIntervalSinceNow)
return timePassed < time
}
else
{
return false
}
}
}
Now, be warned, I barely tested this. Playground isn't complaining and from the looks of it, this should work. Now, just use the class like so:
var myCountdownTimer = CountdownTimer(countDownFrom: 300)
// and then whenever we want to start the countdown:
myCountdownTimer.start()
// and then whenever we want to check if the clock's still "ticking", so to speak:
myCountdownTimer.isValid()
// and if we want to restart the timer:
myCountdownTimer.time = NSTimeInterval(900) // we can change the time if we want
myCountdownTimer.start()
Essentially, all a CountdownTimer object does is save the exact time start() is called to a variable called startTime. Note that NSDate() by default is set to the time-and-date it's created. Then isValid() simply checks to see if the timePassed is less than whatever time the timer was set to count down from; if it is, then it returns true.
I tried this code on playground of Xcode 6.1, And It worked fine.
That's strange...
let someValue: Double = 60.0
var timeInterval = NSTimeInterval(someValue)
println(timeInterval)

How to synchronize different actions in Swift Language for IOS

I created a timer in one class, and tried to do something else in another class while timer works, and do other thing while timer stops. For example, show every second when timer works. I simplified the code as below. How to realize that?
import Foundation
import UIView
class TimerCount {
var timer: NSTimer!
var time: Int!
init(){
time = 5
timer = NSTimer.scheduledTimerWithTimeInterval( 1.0 , target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update(){
if(time > 0) {
time = time - 1
// do something while timer works
}
else{
timer.invalidate()
timer = nil
time = 5
}
}
}
class Main: UIView {
var Clock: TimerCount!
override func viewDidLoad() {
Clock = TimerCount()
//? do something else while clock works
// ? do other things while clock stops
// FOR EXAMPLE: show every second when timer works
if(Clock.time > 0){
println(Clock.time)
}else{
println("clocker stops")
}
}
}
viewDidLoad is most likely only going to be called once. You could simply make the update method be in your Main object and then pass that instance of main and that update method into the scheduledTimerWithTimerInterval call. Otherwise you need a new method in the Main class to call from the timerCount class and pass in the int for the current time.
This is in your Main class:
func updateMethodInMain(timeAsInt: Int){
//do stuff in Main instance based on timeAsInt
}
This is what you have in your timer class:
func update(){
if(time > 0) {
time = time - 1
instanceNameForMain.updateMethodInMain(time)
}
else{
timer.invalidate()
timer = nil
time = 5
}
}
}

Resources