confused human
confused human

Reputation: 421

Continuously check for response in Swift

I have a boolean variable called flag with initial value of false. Based on a successful process, it's set to true. There is a button alert, when tap it, it checks for flag's value along with a spinning image on UI, if flag is true, then a success message should displayed. otherwise, it should keep continuing response check (ten times for 5 seconds).

This is my functionality. I've been using NStimer to achieve this. Here is the code snippet:

var timer = NSTimer()
var count = 10
var flag: Bool = false 
@IBOutlet weak var alert: UIButton!

@IBAction func alertAction(sender: AnyObject) {
  timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: #selector(ViewController.prints), userInfo: nil, repeats: true)
}

func prints(){
    if(count > 0)
    {
       if flag == false{
        **Spinning Image**
            count -= 1
       } else {
       count = 0
       }

    } else {
        timer.invalidate()
    }
}

The spinning image stops and continues after every 5 seconds ( in case response takes more than 5 seconds). I wish to spin the image continuously without a break. Can someone please help?

Thanks in advance!

Upvotes: 0

Views: 1131

Answers (2)

Carien van Zyl
Carien van Zyl

Reputation: 2873

From what I understand, this code will do what you intend. If you are using a UIActivityIndicator. Ensure to start it where I started the rotationAnimation and stop it when invalidating your timer.

Swift 3 Example

@IBOutlet weak var pin: UIImageView!
var timer: Timer?
var count: Int = 5
var flag: Bool {
    return count == 0
}

@IBAction func buttonPressed(_ sender: AnyObject) {
    let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
    rotationAnimation.fromValue = 0
    rotationAnimation.toValue = 2 * M_PI
    rotationAnimation.duration = 0.6
    rotationAnimation.isCumulative = true
    rotationAnimation.repeatCount = Float.infinity
    pin.layer.add(rotationAnimation, forKey: "rotate")

    timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(prints), userInfo: nil, repeats: true)
}

func prints() {
    if flag {
        pin.layer.removeAllAnimations()
        timer?.invalidate()
    } else {
        count = count - 1
    }
}

Upvotes: 1

Pavel Zdenek
Pavel Zdenek

Reputation: 7293

Polling is the most desperate asynchronous pattern and almost always wrong. Learn a bit about value observation and reactive pattern.

var flag = false {
  didSet {
    if flag {
      // stop spinning
    }
  }
}

func alertAction() {
  // start spinning
}

Upvotes: 2

Related Questions