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!
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.
@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
}
}