Timer only executing function once - swift

So the timer works once but after the first time it doesnt work anymore... What's the problem and how can it be fixed? Thanks!
override func viewDidLoad() {
super.viewDidLoad()
let myTimer : Timer = Timer.scheduledTimer(timeInterval: 7, target: self, selector: (selector: "functionOne"), userInfo: nil, repeats: true)
}
}
func functionOne()
{
print("hello")
}

Try this code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Timer.scheduledTimer(timeInterval: 7.0, target: self, selector: #selector(functionOne), userInfo: nil, repeats: true)
}
func functionOne () {
print("hello")
}
Output:

Related

How to remove focus from UIButton after Timer has expired (tvOS)

I'm setting up a simple tvOS application with a menu dock (Stack view containing buttons) at the bottom. After 5 seconds of inactivity I want the dock to hide (move down, out of view) and remove the focus from the currently focused button. The dock should reappear and re-focus on remote control activity. With the following code the dock hides, but just once, after the app has launched. Any help would be much appreciated!
#IBOutlet weak var menuDock: UIStackView!
var timer = Timer()
func resetTimer() {
timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ViewController.hideDock), userInfo: nil, repeats: true)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.showDock))
self.view.addGestureRecognizer(tapRecognizer)
}
#objc func hideDock() {
UIView.animate(withDuration: 0.5, animations: {
self.menuDock.frame.origin.y += 240
}, completion: nil)
timer.invalidate()
}
#objc func showDock() {
UIView.animate(withDuration: 0.5, animations: {
self.menuDock.frame.origin.y -= 240
}, completion: nil)
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.hideDock), userInfo: nil, repeats: true)
timer.invalidate()
}
#IBOutlet weak var menuDock: UIStackView!
var timer = Timer()
func resetTimer() {
timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ViewController.hideDock), userInfo: nil, repeats: true)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.showDock))
self.view.addGestureRecognizer(tapRecognizer)
}
#objc func hideDock() {
UIView.animate(withDuration: 0.5, animations: {
self.menuDock.frame.origin.y += 240
self.menuDock.arrangedSubviews.forEach{
($0 as? UIButton)?.isEnabled = false
}
self.setNeedsFocusUpdate()
self.updateFocusIfNeeded()
}, completion: nil)
timer.invalidate()
}
#objc func showDock() {
UIView.animate(withDuration: 0.5, animations: {
self.menuDock.frame.origin.y -= 240
self.menuDock.arrangedSubviews.forEach{
($0 as? UIButton)?.isEnabled = true
}
self.setNeedsFocusUpdate()
self.updateFocusIfNeeded()
}, completion: nil)
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.hideDock), userInfo: nil, repeats: true)
timer.invalidate()
}

Timer function crashes app

import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
var timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(ViewController.runTimedCode), userInfo: nil, repeats: true)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#objc func runTimedCode() {
imageView.image = UIImage(named: "card10")
}
}
This code gives me the message "unrecognized selector sent to instance" but i do not know what the problem is. Can someone please help me? :)
Try this instead:
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
var timer: Timer? = nil
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(ViewController.runTimedCode), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#objc func runTimedCode() {
imageView.image = UIImage(named: "card10")
}
}
you have to call the function like bellow.
var timer:Timer?
override func viewDidLoad(){
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.runTimedCode), userInfo: nil, repeats: true)
}
#objc func runTimedCode(){
print("timer is calling")
}

Xcode Swift 3: Timer and Segue View Controller Error

This code is in ViewController 1. goToMainUI is assigned to the segue connection ID between ViewController 1 and 2. Also, the storyboard ID for ViewController 2 is the same (goToMainUI). After the timer is finished, there is an error and the ViewControllers do not switch. Anyone know what the problem is? Thanks!
override func viewDidLoad() {
super.viewDidLoad()
let timer = Timer.scheduledTimerWithTimeInterval(8.0, target: self, selector: #selector(timeToMoveOn), userInfo: nil, repeats: false)
func timeToMoveOn() {
self.performSegue(withIdentifier: "goToMainUI", sender: self)
}
Try this code:
Note: Code tested in Swift 3.
Step 1: First set storyboard Segue Identifier
Step 2:
let emptyString = String() // Do nothing
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Timer.scheduledTimer(timeInterval: 8.0, target: self, selector: #selector(timeToMoveOn), userInfo: nil, repeats: false)
}
func timeToMoveOn() {
self.performSegue(withIdentifier: "goToMainUI", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "goToMainUI") {
let dest = segue.destination as! viewTwo // viewTwo is your destination ViewController
dest.emptyString = emptyString
print("Segue Performed")
}
}
In your ViewTwo add this above viewDidLoad method.
var emptyString = String()

NSTimer() - timer.invalidate not working on a simple stopwatch?

I'm kind of at a wall of what to do, the program runs, but the timer.invalidate() does not work? Any tips are welcome.
I worked with this program in the past and worked through it and the timer.invalidate() worked flawlessly. I do not believe that it has to do with the fact that I put it into a function because before it wasn't working when I was just typing "timer.invalidate()" instead of "stop()"
Whenever I click the button Cancel on the iOS simulator it just resets it back to 0, but keeps counting.
Thanks in advance.
import UIKit
class ViewController: UIViewController {
var timer = NSTimer()
var count = 0
#IBOutlet weak var timeDisplay: UILabel!
#IBAction func playButton(sender: AnyObject) {
//play button
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
}
#IBAction func resetTimer(sender: AnyObject) {
//cancel button
stop()
count = 0
timeDisplay.text = "0"
}
#IBAction func pauseButton(sender: AnyObject) {
stop()
}
func result() {
count++
timeDisplay.text = String(count)
}
func stop () {
timer.invalidate()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In playButton() you are defining another timer, that can't be invalidated from outside this function - so by calling timer.invalidate() you invalidate just var timer = NSTimer() which doesn't carry any set timer in it.
So replace
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
with
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("result"), userInfo: nil, repeats: true)

NSTimer hangs program after firing

I am creating a timer inside my ViewController. After it fires once, the program ceases to respond to any further UI events.
I create the timer inside of ViewDidLoad() with:
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "initTimerFired", userInfo: nil, repeats: false)
with timer function (defined as method of ViewController):
func initTimerFired(){
println("Timer fired")
}
It successfully fires, but thereafter the program hangs and does not respond to UI events. If I set repeat = true then it runs a couple of times before quitting with EXC_BAD_ACCESS.
I have looked at many different answers and examples, and I can't see what I am doing wrong.
I am running this on an iOS simulator, using xcode 6.1.
Here is an update. Thanks to the suggestions and code provided in the first answer, I have something working. However, my code, which looks to me to be the same, does not work. In order to implement things within the context of a larger project, I want to know how to avoid the errors I am seeing. For instance, this works:
class ViewController: UIViewController {
#IBOutlet weak var strConsole: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
initTaskManager()
}
func initTaskManager(){
let taskManager = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateTask", userInfo: nil, repeats: true)
}
func updateTask(){
self.strConsole.text = "\(strConsole.text!)Abc"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
But this version does not. Only the function names have changed!:
class ViewController: UIViewController {
#IBOutlet weak var strConsole: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
initTimer()
}
func initTimer(){
let timer1 = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "initTimerFired", userInfo: nil, repeats: true)
}
func initTimerFired(){
self.strConsole.text = "\(strConsole.text!)Abc"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Do not use: initTimerFired, change to something else like: handleTimer,
init as a prefix of the function name may confuse Xcode
See here:
https://developer.apple.com/library/ios/documentation/swift/conceptual/buildingcocoaapps/InteractingWithObjective-CAPIs.html
you have to do like this:
import UIKit
import AVFoundation
class ViewController: UIViewController {
#IBOutlet weak var strConsole: UILabel!
func startTaskManager(){
let taskManager = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTask", userInfo: nil, repeats: true)
}
func updateTask(){
self.strConsole.text = "\(strConsole.text!)Abc"
}
override func viewDidLoad() {
super.viewDidLoad()
startTaskManager()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}