Q.H. Q.H. - 5 months ago 14
Swift Question

All NSTimers running after a previous timer that has been invalidated cease execution instead of continuing to run

In my implementation I am running multiple timers at once on a UITableView and when one timer finishes, I invalidate it and allow it to be removed from said view. Currently the problem I am running into is that when one timer is removed, all others after it cease execution.

public class TimerManager{
static let instance = TimerManager()
private var delegates = [TimerDelegate]()
var currentTimers = [TimerObject]()

public func timerAdded(timer: TimerObject){
self.currentTimers.append(timer)
timer.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(persistTimer(_:)), userInfo: "\(TimerManager.instance.currentTimers.count-1)", repeats: false)
timer.isRunning = true
for delegate in delegates{
delegate.startTimer(self.currentTimers[self.currentTimers.count-1])
}
}

@objc public func persistTimer(timer: NSTimer){
if let indexString = timer.userInfo as? String{
if let index = Int(indexString){
if let currentTimer = self.currentTimers[safe: index]{
if currentTimer.isRunning{
currentTimer.timeDuration -= 1
for delegate in delegates{
delegate.timerStarted(index)
}
}
}
}
}

}

public func addTime(timerId: Int, amount: Int){
for delegate in delegates{
delegate.addTimeToTimer(timerId, amount: amount)
UIApplication.sharedApplication().cancelLocalNotification(currentTimers[timerId].notification)
currentTimers[timerId].notification.fireDate = NSDate(timeIntervalSinceNow: Double(currentTimers[timerId].timeDuration))
}
}

public func subtractTime(timerId: Int, amount: Int){
for delegate in delegates{
delegate.subtractTimeFromTimer(timerId, amount: amount)
UIApplication.sharedApplication().cancelLocalNotification(currentTimers[timerId].notification)
currentTimers[timerId].notification.fireDate = NSDate(timeIntervalSinceNow: Double(currentTimers[timerId].timeDuration))
}
}

public func removeDelegate(removedDelegate: TimerDelegate){
for i in 0..<delegates.count{
if delegates[i] === removedDelegate{
delegates.removeAtIndex(i)
}
}
}

public func cancelTimer(timerId: Int){
let currentTimer = currentTimers[timerId]
currentTimer.timer.invalidate()
UIApplication.sharedApplication().cancelLocalNotification(currentTimer.notification)
currentTimers.removeAtIndex(timerId)
}

private init() {}
}


That is my TimerManager singleton above.
Below is my delete logic:

//Delete cell functionality
public override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if( editingStyle == .Delete){
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let deletedTimer = TimerManager.instance.currentTimers[indexPath.row]
if (deletedTimer.isRunning){
deletedTimer.timer.invalidate()// <-- invalidates all timers for some reason
UIApplication.sharedApplication().cancelLocalNotification(deletedTimer.notification)
}
TimerManager.instance.currentTimers.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
self.tableView.frame = CGRect.init(x: 0, y: 100, width: screenWidth, height: screenHeight * 0.0625 * CGFloat(TimerManager.instance.currentTimers.count))
}
}


This is how I start a timer:

public func startTimer(timer: TimerObject) {
let newIndexPath = NSIndexPath(forRow: TimerManager.instance.currentTimers.count-1, inSection: 0)
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
self.view.frame = CGRectMake(0, 100, screenWidth, screenHeight * 0.0625 * CGFloat(TimerManager.instance.currentTimers.count))
self.view.alpha = 0.95

}


This is what my TimerObject consists of:

public class TimerObject{
var alreadySet = false
var isRunning = false
var timer = NSTimer()
var timeDuration = Int()
var timerString = String()
var doneString = String()
let notification = UILocalNotification()

init(timeDuration: Int, timerString: String, doneString: String){
self.timeDuration = timeDuration
self.timerString = timerString
self.doneString = doneString
notification.alertBody = doneString
}
}


Instantiation of a TimerObject:

private func setTextLinks(string: String){
if let timersForInstruction = parsedOutTimers{
stepTextView.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.redColor()]
for timer in timersForInstruction{
stepTextView.addLink(string.substringFromRange(timer.range)) {
let newTimer = TimerObject.init(timeDuration: timer.lowerBound * 60, timerString: self.stepTitle
newTimer.notification.fireDate = NSDate(timeIntervalSinceNow: Double(newTimer.timeDuration))
TimerManager.instance.timerAdded(newTimer)
}
}
stepTextView.processLinks()
}
}


I would say this is where it is used:

//where we update the cells
public func timerIsRunning(timerIndex: Int){
if let currentTimer = TimerManager.instance.currentTimers[safe: timerIndex]{
guard let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath.init(
forRow: timerIndex,
inSection: 0)) as? TimerCell else { return }
if currentTimer.timeDuration > 0{
currentTimer.timeDuration -= 1
cell.timerDisplay.text = "\(currentTimer.timerString) \t\t\t - \(currentTimer.timeDuration / 60):\((currentTimer.timeDuration % 60).format("02")) + "
cell.timerDisplay.processLinks()
}else if(currentTimer.timeDuration <= 0){
currentTimer.isRunning = false
cell.timerDisplay.text = "Finished"
currentTimer.timer.invalidate()
currentTimer.notification.fireDate = NSDate(timeIntervalSinceNow: 0)
currentTimer.notification.alertBody = currentTimer.doneString
currentTimer.notification.alertAction = "Ok"
if(self.isBeingPresented()){
NSNotificationCenter.defaultCenter().postNotificationName("timerDidFinish", object: currentTimer.notification.alertBody)
}
if(UIApplicationState.Background == UIApplication.sharedApplication().applicationState){
UIApplication.sharedApplication().scheduleLocalNotification(currentTimer.notification)
}
}else{
//handle pause
}
}

}


I sincerely hope this is enough information to work with.
Any solutions or alternatives would help greatly.

Answer

I was able to fix my own problem by instead instantiating a new timer for each object, there's just one timer that's updating the view for all objects.

private var timer = NSTimer()
    var isFirstTimer = false


    public func timerAdded(newTimerObject: TimerObject){
        if(isFirstTimer){
            self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(persistTimers(_:)), userInfo: nil, repeats: true)
        }
        self.currentTimers.append(newTimerObject)
        newTimerObject.isRunning = true
        for delegate in delegates{
            delegate.startTimer(self.currentTimers[self.currentTimers.count-1])
        }
    }

    @objc public func persistTimers(timer: NSTimer){
        for i in 0..<self.currentTimers.count{
            if let currentTimer = currentTimers[safe: i]{
                if(currentTimer.isRunning){
                    currentTimer.timeDuration -= 1
                    for delegate in delegates{
                        delegate.timerStarted(i)
                    }
                }
            }
        }
    }

This is ultimately what I ended up changing in my singleton declaration and I ended up removing the

currentTimer.timeDuration -= 1

line from the timerStarted function into the persistTime function... I realize my implementation and style have a lot to be desired but it's a start. Only 2 weeks into iOS programming after all.

EDIT:

the "[safe: ]" extension I added is for safe index access:

public extension CollectionType{
    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}