Reputation: 569
In the settings for my app, there is a switch allowing the user to turn iPhone's flash on or off (flash is used to indicate certain points in app logic while it's running). What I want to implement is this: when the user toggles this switch on, I want it to, well, flash for a split second to indicate its 'ON' state.
Now, I know how to set torchMode
on or off - this is implemented in the app itself, but I'm not sure how to correctly make it 'blink' for settings purpose. One of the ways I thought of is to use following code (toggleFlash()
is a static method for toggling torchMode
implemented in main code):
UIView.animate(withDuration: 1.0, animations: {
ViewController.toggleFlash(on: true)
}, completion: { (_) in
ViewController.toggleFlash(on: false)
})
This does make it 'blink', but only for a moment - not 1 second. Besides, I'm not so sure if it's at all correct to use animate
for this purpose. Another idea is to use Thread.sleep
, but this looks like an even worse practice.
Can someone recommend better solutions?
Upvotes: 0
Views: 84
Reputation: 923
Probably something like this:
func flash() {
ViewController.toggleFlash(on: true)
let time = DispatchWallTime.now() + DispatchTimeInterval.seconds(1)
DispatchQueue.main.asyncAfter(wallDeadline: time) {
ViewController.toggleFlash(on: false)
}
}
wallDeadline is reliable and the solution is packed in one function.
Upvotes: 2
Reputation: 2751
You could use a timer.
func flashForOneSecond() {
ViewController.toggleFlash(on: true)
flashOffTimer = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(self.switchFlashOff), userInfo:nil, repeats:false)
}
@objc func switchFlashOff() {
ViewController.toggleFlash(on: false)
}
Upvotes: 2