Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop that checks it's condition every second in swift

How does one create a while loop that checks it's condition every second?

maybe something like this:

while (isConditionSatisfied){
// wait for 1 second and than check again
}

EDIT: The system calls this function bannerViewDidLoadAd at random times. If it calls it at inappropriate time(condition is unsatisfied-my app is performing some other animation), I would like to defer its implementation(just an UIView animation) until the condition is satisfied(my app has finished animating, now the implementation should be executed). I was thinking I could check the condition in a while loop every second, but as you guys said..this is a bad idea.

like image 924
potato Avatar asked Dec 01 '22 14:12

potato


2 Answers

Using while loop like this will create an infinite loop actually. You should use Timer().

timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.loop), userInfo: nil, repeats: true)

And then

@objc
func loop() {
    if yourCondition {
        // your code here
        timer.invalidate()
    }
}

Make sure you declare timer with your other variable declarations, so it can be invalidated once your condition has been met:

var timer: Timer!
like image 125
Sahil Kapoor Avatar answered Dec 06 '22 15:12

Sahil Kapoor


Swift loop with interval

iOS 10

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in   
    if someCondition {
        timer.invalidate()
    }
}

*withTimeInterval - number of seconds

like image 42
yoAlex5 Avatar answered Dec 06 '22 15:12

yoAlex5