Search code examples
iosswiftwhile-loop

while loop that checks its condition every second


How does one create a while loop that checks its condition every second?

Maybe something like this:

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

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.


Solution

  • 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!