Swift Deleting Table View Cell When Timer Expires

How to delete custom cell with timer in UITableView?

Don't call refresh method after deleting the row.Hope this help.

Creating a timer to delete a tableviewcell user post?

You are right that timers get killed if your app is terminated. They get suspended if your app is suspended, as well. Pretty much any time the user swaps to another app and stays there for more than a few seconds this approach won't work.

You could save an array of expire dates to user defaults, and any time the app is launched/returns to the foreground, you could check the array of expire dates. If an expire date has passed, you'd delete that post from Firebase. (Actually you'd probably save an array of dictionaries where one key was the date and another key was the record ID so you could find the record.)

You could also create local notifications using the expire date of the entry as the fire date of the notifiacation. If your app is running it would get the notification in the background and you could trigger the delete. If not it would show a message to the user and if the user asks to open the app you could then check your array of expire dates as above.

Time Countdown on each cell of UITableView in iOS

I’d rather suggest you to create a custom cell and in that cell class, create a timer based on your value from server. This way every cell would have its own timer. That’s what you probably want.
In your current implementation, your timer handler is unaware of cell or its row number.

class MyCustomCell: UITableViewCell {
@IBOutlet weak private var myLabel: UILabel!

private var timer: Timer?
private var timeCounter: Double = 0

var expiryTimeInterval: TimeInterval? {
didSet {
startTimer()
}
}

private func startTimer() {
if let interval = expiryTimeInterval {
timeCounter = interval
if #available(iOS 10.0, *) {
timer = Timer(timeInterval: 1.0,
repeats: true,
block: { [weak self] _ in
guard let strongSelf = self else {
return
}
strongSelf.onComplete()
})
} else {
timer = Timer(timeInterval: 1.0,
target: self,
selector: #selector(onComplete),
userInfo: nil,
repeats: true)
}
}
}

@objc func onComplete() {
guard timeCounter >= 0 else {
timer?.invalidate()
timer = nil
return
}
myLabel.text = String(format: "%d", timeCounter)
timeCounter -= 1
}
}

Usage

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCustomCell

cell.expiryTimeInterval = 10

return cell
}

Go to you cell nib or storyboard and change the class name for TimeCell to MyCustomCell



Related Topics



Leave a reply



Submit