Swift - how to run multiply timers? - ios

In my app I have a view, and I want this view to be dismissed everytime it is shown after 8 seconds. In order to do that I created a timer inside view creation function that hides view after firing. It works. But in some cases I want to present two copies of the view I want both be dismissed after time it was created +8 seconds. Issue is that timer works only once - it hides one copy of view, and second remains on screen
My code is
func presentShowStatusShort(text text:String) {
pointsShort = NSBundle.mainBundle().loadNibNamed("helperShowStatusShort", owner: self, options: nil).first! as! helperShowStatusShort
pointsShort?.frame.size.width = self.view.bounds.width
if pointsShortOnScreen {
pointsShort!.frame.origin.y = pointsShort!.frame.origin.y + 39
}
pointsShort?.text.text = "\(text.uppercaseString)"
pointsShort!.dismissButton.addTarget(self, action: "dismissShowStatusShort", forControlEvents: UIControlEvents.TouchUpInside)
var timer = NSTimer.scheduledTimerWithTimeInterval(8, target: self, selector: "dismissShowStatusShort", userInfo: nil, repeats: false)
pointsShortOnScreen = true
view.addSubview(pointsShort!)
}
func dismissShowStatusShort() {
pointsShortOnScreen = false
UIView.animateWithDuration(0.5, animations: {
self.pointsShort?.frame.origin.y = (self.pointsShort?.frame.origin.y)! - 64
}, completion: {
finished in
self.pointsShort?.removeFromSuperview()
})
}

From an OOP point of view you should create a class to help you with this. The class would own the timer and maintain a reference to the view. When the timer expires it calls a callback, passing itself as the parameter, so the controller can get the associated view and dismiss it.
All of the instances of this class would be stored in an array instance variable on the controller so you can add multiple and remove each one once it expires.

Related

Hiding removing SubView from a different file in swift

I am loading a progress view from this file into a different view controller, it is displaying fine but It will not remove. I've tried isHidden, removeFromSuperview(), making the alpha=0, but nothing is working. How can I get rid of it?
func timerAction(){
let progressHUD = ProgressHUD(text: "Taking Reading")
if(timerCounter <= 20){
self.vc!.view.addSubview(progressHUD)
timerCounter += 1
} else {
timer.invalidate()
timerCounter = 0
progressHUD.removeFromSuperview()
}
}
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true)
Each time the timer is called a new subview is added to the view controller. Add the subview 'progressHUD' just once and update it instead.

Strange Behavior with UITapGestureRecognizer

I implemented a SnackBar / Toast Message in Swift 4 which allows the developer to set the following display duration (enum) and with the following behaviour:
.long / .short: Timer gets fired and dismisses the SnackBar OR the user taps the view and it also dismisses
.constant: No Timer, only TapGesture to dismiss
Now in the first case (.long / .short) the SnackBar reacts as expected. Either the Timer fires or the user taps and the view gets dismissed.
In the second case (.constant) - where there is no timer - the Tap gesture is not recognised and the view doesn't get dismissed
here are the three functions:
private func defineDismissMode(){
switch self.message.duration {
case .short, .long:
self.setTimer()
case .constant:
self.setTapGesture()
}
}
private func setTimer(){
guard self.timer == nil else {return}
self.timer = Timer.scheduledTimer(timeInterval: self.message.duration.rawValue, target: self, selector: #selector(self.dismissSnackBar), userInfo: nil, repeats: false)
self.setTapGesture()
}
private func setTapGesture() {
self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissSnackBar))
self.snackView.addGestureRecognizer(self.tapGestureRecognizer!)
}
#objc private func dismissSnackBar(){
...
}
Anyone a clue why when setTapGesture() is called after setTimer() it works and a tap triggers self.dismissSnackBar , but when called without setTimer() the UITapGestureRecognizer is not triggered?
Note: Yes I checked that case: .constant -> setTapGesture() gets called

Timer object only calling selector once when firing

I'm trying to create an app that is similar to SnapChat when it takes videos. You are supposed to hold down a button to start taking a video and then release it when you are done. I'm trying to implement a timeout feature after 7 seconds and also a progress bar by using a Timer object. However, when I try fire the timer, it only calls the given selector once and that's it even though I tell it to repeat itself.
Here's my code to initialize the button:
let photoButton:UIButton = {
let but = UIButton(type: .custom)
but.layer.cornerRadius = 40
but.layer.borderColor = UIColor.white.cgColor
but.layer.borderWidth = 4
but.clipsToBounds = true
but.addTarget(self, action: #selector(takeVideo), for: .touchDown)
but.addTarget(self, action: #selector(stopVideo), for: [.touchUpInside, .touchUpOutside])
but.translatesAutoresizingMaskIntoConstraints = false
return but
}()
Here's the function takeVideo that is called when the user starts to hold down the button. I initialize and fire the Timer object here:
#objc func takeVideo() {
progressBar.isHidden = false
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateProgressbar), userInfo: nil, repeats: true)
startTime = Date().timeIntervalSince1970()
timer?.fire()
}
This is the function stopVideo where I invalidate the Timer object:
#objc func stopVideo() {
timer?.invalidate()
// stop video
}
And this is the updateProgressBar function:
#objc private func updateProgressbar() {
let maxLength = 7.0
let difference = Date().timeIntervalSince1970 - startTime!
progressBar.progress = Float(difference / maxLength)
if difference >= maxLength {
stopVideo() // Invalidates the timer and will stop video.
}
}
It seems that this person has had a similar issue, but when I tried to incorporate his answer of presenting the current view controller using async, it still doesn't work. Here's how I present the video recording view controller:
let recorder = RecorderViewController()
recorder.db = db
DispatchQueue.main.async(execute: {
self.present(recorder, animated: true, completion: nil)
})
Edit: I've fixed the incorrectness concerning the Timer object's fireDate property (the fix is also fixed in the above code). It fixed my problem.

NSTimer to Change Text

Sorry if this is a really basic questions, but I can’t seem to work it out, so I thought I would ask the experts.
I’ve got a timer for my project that counts down and updates a label according to what is stored in an array.
var array : String[]()
var x = 0
#IBAction func playBtnPressed(sender: UIButton)
{
timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(PlayVC.update), userInfo: nil, repeats: true)
}
func update()
{
if x < array.count {
let item = array[x]
aLbl.text = array.itemTitle
x += 1
}
}
My problem is that the text is only updated after the first countdown and 60 seconds is a long time to wait lol.
I would actually like the first String in my array to appear as soon as the button is tapped.
Is there a way to set the text at the very beginning of the countdown?
Thank you for your help :)
So you want to update a label every minute. And you also want to update it immediately after the button is pressed. Hopefully I didn't misunderstand the question.
It's actually as easy as adding this line before the timer = NSTimer ... line:
update()
Note that your current code can cause two or more timers to be created and run when the button is pressed more than once. You might not want this.
To stop the timer when the button is pressed a second time, do this:
if timer == nil {
timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: #selector(PlayVC.update), userInfo: nil, repeats: true)
} else {
timer.invalidate()
timer = nil
}
To do nothing when the button is pressed a second time jus remove the else part.

Xcode delayed button

Hello I'm new here and new to app development but I'm building an app with multiple views and I would like to add a button that will go to the next view but the user will have to wait 3 seconds or so on each view before the button is available to be tapped.
You could perform a method after a delay with reveals or enables your button,
[self performSelector:#selector(yourMethod) withObject:nil afterDelay:3.0];
if you want the delay to happen after button tap then have a look at the below code
let tapGesture = UITapGestureRecognizer(target: self, action: "tapAction")
tapGesture.numberOfTapsRequired = 1
Your_Button_name.addGestureRecognizer(tapGesture)
#IBAction func tapAction()
{
Your_Button_name.disable=true
//Delay function to enable your button
NSTimer.scheduledTimerWithTimeInterval(Your_time_value_delay, target: self, selector: Selector("enablefunc"), userInfo: nil, repeats: false)
// DO SOMETHING WHICH YOU WANT TO DO.....
}
func enablefunc()
{
Your_Button_name.disable=false
}
Hope this helps. You can modify it based on your requirement....

Resources