How to add countdowntimer which will run in whole iOS application? - ios

I need to add a global timer of 60 minutes in the application which will show in all ViewControllers.
But not able to implement this feature.
I have implemented timer in one ViewController till now.
Here is my code:
var timerCount = 3600
var timer = Timer()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
func update() {
if(timerCount > 0){
let minutes = String(timerCount / 60)
let seconds = String(timerCount % 60)
timeLbl.text = minutes + ":" + seconds
timerCount -= 1
}
else {
timer.invalidate()
let vc = storyboard?.instantiateViewController(withIdentifier: "NavigateViewController")
navigationController?.pushViewController(vc!, animated: true)
}
}
I need to show this timer value in every ViewController of the application.

// Create class TimerManager
class TimerManager {
var timerCount = 3600
static let sharedInstance = TimerManager()
var timer: Timer?
init() {
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}
#objc func update() {
if(timerCount > 0){
let minutes = String(timerCount / 60)
let seconds = String(timerCount % 60)
timerCount -= 1
}
else {
self.timer?.invalidate()
}
}
}
// At view Controller you can access timerCount
print(TimerManager.sharedInstance.timerCount)

You should display it in a separate UIWindow instance. Put the label in a separate View Controller and refer to answer 42 from this post:
To create a new UIWindow over the main window

// Create class TimerManager
class TimerManager {
var timerCount = 3600
static let sharedInstance = TimerManager()
var timer: Timer!
init() {
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}
#objc func update() {
if(timerCount > 0){
let minutes = String(timerCount / 60)
let seconds = String(timerCount % 60)
timerCount -= 1
}
else {
self.timer?.invalidate()
}
}
}
// At view Controller you can access timerCount
print(TimerManager.sharedInstance.timerCount)

Related

Swift 2 - Timed Actions one second apart?

I'm trying to get output like so:
1 (then a one second delay)
Hello
2 (then a one second delay)
Hello
3 (then a one second delay)
Hello
But instead I get
1
2
3 (then a one second delay)
Hello
Hello
Hello
Here's my for loop invoking the NSTimer
var timer = NSTimer()
for i in 1...3 {
print("\(i)");
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(MainVPScreenViewController.printTest), userInfo: nil, repeats: false)
}
And here's the selector method:
func printTest() {
print("Hello")
}
Thanks in advance for any help you can provide
Try this solution without NSTimer:
var i = 1
func printHello() {
print(i)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
print("Hello")
i +=1
if i <= 3 {
printHello()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
printHello()
}
I need 2 NSTimers to do this, this is my approach
class ViewController: UIViewController {
var i = 1
override func viewDidLoad() {
super.viewDidLoad()
beginPrinting()
}
func beginPrinting() {
var timer2 = NSTimer()
if(i <= 100)
{
timer2 = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.printWithDelay), userInfo: nil, repeats: false)
}
}
func printWithDelay()
{
var timer = NSTimer()
print("\(i)");
i += 1
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.printTest), userInfo: nil, repeats: false)
}
func printTest() {
print("Hello")
beginPrinting()
}
}
Hope this helps you
Use timer with repeat to true. So in your view controller would be like this
var timer = NSTimer()
var counter = 0
var max = 10
let delay = 1 // in second
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self,
selector: #selector(self.printTest), userInfo: nil, repeats: true)
}
func printTest() {
counter += 1
print(counter)
print(hello)
if counter == maxNumber {
timer.invalidate()
}
}
This does it with repeat false, and is set up to be in a playground:
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
#objc class Foo: NSObject {
static var timer = NSTimer()
var i:Int
override init() {
Foo.timer = NSTimer()
i = 1
}
func schedule() {
print("\n\(i)");
i += 1
Foo.timer = NSTimer.scheduledTimerWithTimeInterval(1.0,
target: self,
selector: #selector(printTest),
userInfo: nil,
repeats: false)
}
#objc func printTest() {
print("Hello")
if i < 5 {
schedule()
}
}
}
let bar = Foo()
bar.schedule()

How to change the NSTimeInterval of an NSTimer after X seconds?

I'm making an app in swift 2 where there is two timers. After 10 seconds I would like another timer to go faster. I have tried doing it like this but it didn't work (I'm trying to change the var time to 1):
#IBOutlet var displayTimeLabel: UILabel!
var startTimer = NSTimeInterval()
var timer = NSTimer()
var timer2:NSTimer = NSTimer()
var time = 2.0
#IBAction func Start(sender: UIButton) {
if !timer2.valid {
timer2 = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true)
startTimer = NSDate.timeIntervalSinceReferenceDate()
}
timer = NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: "timer:", userInfo: nil, repeats: true)
}
func timer(timer: NSTimer){
//code
}
func updateTime() {
if displayTimeLabel.text >= "00:10.00"{
print("00:10.00") //works
time = 1 // trying to execute code after 10 seconds(doesn't work)
}
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: NSTimeInterval = currentTime - startTimer
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
displayTimeLabel.text = "\(strMinutes):\(strSeconds).\(strFraction)"
}
If I write print(time) in func timer, after ten seconds it will print 1 instead of 2 but it will still be repeating every two second. Please help. To be clear, I want to be able to change time to 1 instead of 2 after ten seconds. I also don't want to invalidate the timers. The timers are also on repeat = true. Thanks in advance... Anton
A few of things.
First, you can't change the time interval of a repeating NSTimer - you need to invalidate the first timer and schedule a new one for the new interval.
Second a >= comparison on a string won't work for what you are trying to achieve.
Finally, you have fallen into the same bad habit as many Swift programmers and initialised your timer variables needlessly only to subsequently throw those timers away. You should use either an optional or an implicitly unwrapped optional
#IBOutlet var displayTimeLabel: UILabel!
var startTime:NSDate?
var timer : NSTimer?
var timer2: NSTimer?
var time = 2.0
#IBAction func Start(sender: UIButton) {
if (self.timer2 == nil) {
self.time=2.0
self.timer2 = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true)
self.startTime = NSDate()
self.timer = NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: "timer:", userInfo: nil, repeats: true)
}
}
func timer(timer: NSTimer){
//code
}
func updateTime() {
let currentTime = NSDate.timeIntervalSinceNow()
var elapsedTime = -self.startTime!.timeIntervalSinceNow()
if (elapsedTime >10.0 && self.time==2.0) {
timer.invalidate()
self.time=1.0
self.timer = NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: "timer:", userInfo: nil, repeats: true)
}
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
displayTimeLabel.text = String(format: "%02d:%02d.%02d", minutes,seconds,fraction)
}
Just setting time = 1 will not modify timer.
The timeInterval of a timer can not be changed. Your only options are to create a new timer or start it with a timeInterval of 1 and just do nothing every other time timer() is called until the 10 sec have passed.

IOS swift countdown timer will not stop

I am attempting to make a countdown timer that counts down from 60 seconds and then stops when it gets to 0. But for the timer keeps going into negative seconds. Any advice is appreciated. Code:
#IBOutlet var timeCounter: UILabel!
var second = 60
var timer = NSTimer()
var timerRunning = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setTimer()
timerCounting()
}
func setTimer(){
second -= 1
timeCounter.text = "\(second)"
}
func timerCounting(){
if(timerRunning == true){
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setTimer"), userInfo: nil, repeats: true)
timerRunning = true
if second == 0 {
timerRunning = false
timer.invalidate()
}
}
}
You have to move the invalidation into the setTimer function since at its current location will never be triggered because timerCounting is only called once - in the beginning.
func setTimer(){
second -= 1
timeCounter.text = "\(second)"
if second == 0 {
timerRunning = false
timer.invalidate()
}
}
play with this in playground
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
import Foundation
#objc class C:NSObject {
var timer: NSTimer?
var second = 5
func setTimer(){
if c.second < 0 {
print("the timer fires the last time here ...")
timer?.invalidate()
} else {
print(second)
second -= 1
}
}
}
let c = C()
func timerCounting(){
c.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: c, selector: Selector("setTimer"), userInfo: nil, repeats: true)
}
timerCounting()

Create timer on a scroll view

How would I go about creating a timer function on a scroll view.
I have implemented a timer function that works correctly however due to the nature of a scrollView the view controller loads everytime the page is swiped & the timer gets reset.
How would I store the value of the timer from each page of the scrollView, so that it doesn't reset?
Below are my timer functions:
override func viewDidAppear(animated: Bool) {
// Start Timer Variables
startGame()
timerButtonStart()
}
Timer Functions
// Mark : Timer Functions
func startGame() {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
#IBAction func pauseTimer(sender: AnyObject) {
if timerPaused == false {
elapsedTime += startTimeDate.timeIntervalSinceNow
timer.invalidate()
timerPaused = true
} else {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTimeDate = NSDate()
startTime = NSDate.timeIntervalSinceReferenceDate() + elapsedTime
timerPaused = false
}
}
func updateTime() {
var currentTime = NSDate.timeIntervalSinceReferenceDate()
//Find the difference between current time and start time.
var elapsedTime: NSTimeInterval = currentTime - startTime
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
strMinutesGlobal = strMinutes
strSecondsGlobal = strSeconds
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
timerLabel.text = "\(strMinutesGlobal!):\(strSecondsGlobal!)"
}
func timerButtonStart() {
var refreshButton = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self, action: "timer") //Use a selector
navigationItem.leftBarButtonItem = refreshButton
navigationController!.navigationBar.barTintColor = UIColor.greenColor()
title = "Search result"
}
If you want to prevent that your NSTimer gets deallocated when switching view controllers, you could store the NSTimer instance in a separate singleton class instead of the view controller.
class MyTimer {
var sharedInstance = MyTimer()
var timer: NSTimer?
}
With this, you can access the NSTimer instance like this:
MyTimer.sharedInstance.timer
You can change your timer creation code to
if (timer == nil) {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
}
and also when you invalidate your timer you will need to set it to nil. This will only recreate the timer if it doesn't already exist.

How to use a countdown timer to stop a game - iOS [SWIFT] -

My game is supposed to be stopped after 60s. But nothing happens with my timer code.
var timer = NSTimer()
var counter:Int = 60
var labelCounter:SKLabelNode = SKLabelNode()
Here is the code in my GameScene class :
func startTimer()
{
timer = NSTimer.scheduledTimerWithTimeInterval(1.0
, target: self, selector: Selector("updateTimer:"), userInfo: nil, repeats: true)
}
func updateTimer(dt:NSTimer)
{
counter--
if counter == 0 {
timer.invalidate()
removeCountDownTimerView()
} else{
labelCounter.text = "\(counter)"
}
}
func removeCountDownTimerView()
{
scene.view.paused = true
}
thank you for your insight :-)
Try something like this....
override func viewDidLoad() {
super.viewDidLoad()
//calling the wait function
self.callForWait()
}
func callForWait(){
//setting the delay time 60secs.
let delay = 60 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
//call the method which have the steps after delay.
self.stepsAfterDelay()
}
}
func stepsAfterDelay(){
//your code after delay takes place here...
}
I had this in a game. Hope it helps:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
startGame()
}
var startTime = NSTimeInterval()
var timer = NSTimer()
var gameTime:Double = 10
func startGame() {
let aSelector : Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
func updateTime() {
var currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime = currentTime - startTime
var seconds = gameTime-elapsedTime
if seconds > 0 {
elapsedTime -= NSTimeInterval(seconds)
println("\(Int(seconds))")
} else {
timer.invalidate()
}
}
}

Resources