This question already exists:
SWIFT Updating screen in between steps of while loop
Closed 6 years ago.
I'm building an app that simulates Conway's Game Of Life. I'm trying to run an infinite animation when a RUN button is pressed. Here's my code:
//When RUN button is clicked, call run repeat
#IBAction func run(sender: AnyObject) {
UIView.animateWithDuration(3, delay: 2, options: [.Repeat], animations: {self.runrepeat()}, completion: nil)
}
//Run repeat calls run, calculating next generation of the board
func runrepeat() {
board.run()
//Update the appearance of all the buttons based on their new values
for cellButton in self.cellButtons {
cellButton.setTitle("\(cellButton.getLabelText())",
forState: .Normal)
}
}
When the RUN UI button is pressed, I want run() to be called, which should continuously call runrepeat() every 3 seconds. board.run() runs algorithms to determine the configuration of the next generation of cells, and the for cellButton{} loop updates that appearances of all the cells.
However, as is, runrepeat() is only called once, so the next generation appears on the board and the animation stops, without any delays. My RUN button is correctly executing runrepeat(), but only once. I want it to repeat forever.
I tried this too:
//Run repeat calls run, calculating next generation of the board
func runrepeat() {
while(true){
board.run()
//Update the appearance of all the buttons based on their new values
for cellButton in self.cellButtons {
cellButton.setTitle("\(cellButton.getLabelText())",
forState: .Normal)
}
}
}
but the infinite while loop just causes my program to freeze up. The updating of the screen never happens.
Can someone please help me with executing a continuous function call, screen update loop? Please this is due in 4 days.
extension NSTimer {
static public func schedule(delay delay: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
static func schedule(repeatInterval interval: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = interval + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
}
Then, you can call UI updates every 3 seconds like so:
NSTimer.schedule(repeatInterval: 3.0, handler: { timer in
//UI updates
})
Related
In my SpriteKit project when the user starts a new game, the timer starts counting and, every new game, only the first time the app goes background, the timer resets, then the next times works fine(pauses and when the app goes foreground it continues counting), how can I avoid this first time reset?
This is how I handle the timer:
override func didMove(to view: SKView) {
DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
self.myTimer()
})
}
func myTimer() {
run(.wait(forDuration: 1), completion: {
self.timer += 1
print(self.timer)
if(self.timer == 5){
self.goldBottle = true
}
self.myTimer()
})
}
I am using an NSTimer to let the user know the app is working. The progress bar is set up to last 3 seconds, but when running, it displays in a 'ticking' motion and it is not smooth like it should be. Is there anyway I can make it more smooth - I'm sure just a calculation error on my part.
Here is the code:
import UIKit
class LoadingScreen: UIViewController {
var time : Float = 0.0
var timer: NSTimer?
#IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
// Do stuff
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true)
} //close viewDidLoad
func setProgress() {
time += 0.1
progressView.progress = time / 3
if time >= 3 {
timer!.invalidate()
}
}
}
As per Apple iOS SDK docs you can achieve it with the use of next API:
func setProgress(_ progress: Float, animated animated: Bool)
It adjusts the current progress shown by the receiver, optionally animating the change.
Parameters:
progress - The new progress value.
animated - true if the change should be animated, false if the change should happen immediately.
More info on this:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIProgressView_Class/index.html#//apple_ref/occ/instm/UIProgressView/setProgress:animated:
So in your case you should do it like this:
func setProgress() {
time += 0.1
dispatch_async(dispatch_get_main_queue()) {
progressView.setProgress(time / 3, animated: true)
}
if time >= 3 {
timer!.invalidate()
}
}
Also please note that it is a good practice to perform UI updates on main thread, so I just dispatched progress update on main queue.
Hope it will help you.
I'm trying to make a progress bar act as a timer and count down from 15 seconds, here's my code:
private var timer: dispatch_source_t!
private var timeRemaining: Double = 15
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
profilePicture.layer.cornerRadius = profilePicture.bounds.width / 2
let queue = dispatch_queue_create("buzz.qualify.client.timer", nil)
timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 10 * NSEC_PER_MSEC, 5 * NSEC_PER_MSEC)
dispatch_source_set_event_handler(timer) {
self.timeRemaining -= 0.01;
self.timerBar.setProgress(Float(self.timeRemaining) / 15.0, animated: true)
print(String(self.timerBar.progress))
}
dispatch_resume(timer)
}
The print() prints the proper result, but the progress bar never updates, somestimes it will do a single update at around 12-15% full and just JUMP there and then do nothing else.
How can I make this bar steadily flow down, and then execute a task at the end of the timer without blocking the UI thread.
In siburb's answer, he correctly points out that should make sure that UI updates happen on the main thread.
But I have a secondary observation, namely that you're doing 100 updates per second, and there's no point in doing it that fast because the maximum screen refresh rate is 60 frames per second.
However, a display link is like a timer, except that it's linked to the screen refresh rate. You could do something like:
var displayLink: CADisplayLink?
var startTime: CFAbsoluteTime?
let duration = 15.0
func startDisplayLink() {
startTime = CFAbsoluteTimeGetCurrent()
displayLink = CADisplayLink(target: self, selector: "handleDisplayLink:")
displayLink?.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
func stopDisplayLink() {
displayLink?.invalidate()
displayLink = nil
}
func handleDisplayLink(displayLink: CADisplayLink) {
let percentComplete = Float((CFAbsoluteTimeGetCurrent() - startTime!) / duration)
if percentComplete < 1.0 {
self.timerBar.setProgress(1.0 - percentComplete, animated: false)
} else {
stopDisplayLink()
self.timerBar.setProgress(0.0, animated: false)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
startDisplayLink()
}
Alternatively, if you're doing something on a background thread that wants to post updates to UIProgressView faster than the main thread can service them, then I'd post that to the main thread using a dispatch source of type DISPATCH_SOURCE_TYPE_DATA_ADD.
But, if you're just trying to update the progress view over some fixed period of time, a display link might be better than a timer.
You must always update the UI on the main thread. I'm not a Swift expert, but it looks like you're currently trying to update the UIProgressView in the background.
Try updating the UIProgressView on the main queue like this:
dispatch_async(dispatch_get_main_queue(),^{
self.timerBar.setProgress(Float(self.timeRemaining) / 15.0, animated: true)
print(String(self.timerBar.progress))
})
So I am using an NSTimer to let the user know the app is working. The progress bar is set up to last 3 seconds, but when running, it displays in a 'ticking' motion and it is not smooth like it should be. Is there anyway I can make it more smooth - I'm sure just a calculation error on my part....
If anyone could take a look that would be great. Here is the code:
import UIKit
class LoadingScreen: UIViewController {
var time : Float = 0.0
var timer: NSTimer?
#IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
// Do stuff
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true)
}//close viewDidLoad
func setProgress() {
time += 0.1
progressView.progress = time / 3
if time >= 3 {
timer!.invalidate()
}
}
}
Edit: A simple 3 second UIView animation (Recommended)
If your bar is just moving smoothly to indicate activity, possibly consider using a UIActivityIndicatorView or a custom UIView animation:
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
UIView.animateWithDuration(3, animations: { () -> Void in
self.progressView.setProgress(1.0, animated: true)
})
}
Make sure your progressView's progress is set to zero to begin with. This will result in a smooth 3 second animation of the progress.
Simple animated progress (Works but still jumps a bit)
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIProgressView_Class/#//apple_ref/occ/instm/UIProgressView/setProgress:animated:
func setProgress() {
time += 0.1
progressView.setProgress(time / 3, animated: true)
if time >= 3 {
timer!.invalidate()
}
}
Option with smaller intervals. (Not recommended)
Set your timer to a smaller interval:
timer = NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true)
Then update your function
func setProgress() {
time += 0.001
progressView.setProgress(time / 3, animated: true)
if time >= 3 {
timer!.invalidate()
}
}
For continues loader
timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(setProgress), userInfo: nil, repeats: true)
and
func setProgress() {
time += 0.001
downloadProgressBar.setProgress(time / 3, animated: true)
if time >= 3 {
self.time = 0.001
downloadProgressBar.progress = 0
let color = self.downloadProgressBar.progressTintColor
self.downloadProgressBar.progressTintColor = self.downloadProgressBar.trackTintColor
self.downloadProgressBar.trackTintColor = color
}
It's hard to say exactly what the problem is. I would like to see the output if you put a print line in setProgress to print a timestamp. Is it actually firing every tenth of a second? My guess is that it is not.
Why not? Well, the timer schedules a run loop task in the main thread to execute the code in setProgress. This task cannot run until tasks in front of it in the queue do. So if there are long running tasks happening in your main thread, your timer will fire very imprecisely. My first suggestion is that this is perhaps what is happening.
Here is an example:
You start a timer to do something every second.
Immediately after, you start a long running main thread task (for example, you try to write a ton of data to a file). This task will take five seconds to complete.
Your timer wants to fire after one second, but your file-writing is
hogging the main thread for the next four seconds, so the timer can't fire
for another four seconds.
If this is the case, then to solve the problem you would either need to move that main thread work to a background thread, or else figure out a way to do it while returning to the run loop periodically. For example, during your long running main thread operation, you can periodically call runUntilDate on your run loop to let other run loop tasks execute.
Note that you couldn't just increment the progress bar fill periodically during the long running main thread task, because the progress bar will not actually animate its fill until you return to the run loop.
What about proper way for animating changes: animateWithDuration:animations: or CABasicAnimation. You can use this for creating smooth animations
I need a cycle of 5 times of 2.5 seconds in a single cycle, however, that the pressure of a button bait from single cycle without interrupting the scheduling.
I use method fire (with pressed button) for stoping a repeating timer without interrupting its regular firing schedule, but I don't know, subsequent cycles are shorter than the defined 2.5 seconds:
.......
#IBAction func buttonZeroPressed(sender: AnyObject) {
timer.fire()
++addWin
}
......
timer = NSTimer.scheduledTimerWithTimeInterval(2.5, target: self,
selector: Selector("levelOne"), userInfo:nil,repeats: true)
......
func levelOne() {
level = 1
count++
changePhoto()
if (count >= 5) {
timer.invalidate()
}
}
After the 3 pressed button, the timer seems to be 2.5 seconds, and I do not understand why!
The fire() method is how you start a timer that's been created but not scheduled. You want to use invalidate() to stop the timer.
#IBAction func buttonZeroPressed(sender: AnyObject) {
timer.invalidate()
++addWin
}
Your timer will start immediately since you call scheduledTimerWith.... If you wanted to create a timer without starting, you would use:
timer = NSTimer(timeInterval: 2.5, target: self, selector: Selector("levelOne"), userInfo:nil,repeats: true)