Reputation: 801
Here in myAPICall()
method am calling another method I.e., COStatusAPI()
for every 5 seconds upto 90 seconds.
Here COStatusAPI()
is an API call. i.e., Am hitting server for every 5 seconds.
In response I’ll get COStatus as 1 or 0.
If I get COStatus as 1, am stopping the timer and navigating to another viewController and If I get COStatus as 0 for 90 seconds. I am stopping the timer and showing alert.
But here my issue is timer is not getting stop. like, If I get COStatus as 1, in background timer is running. So, after 90 seconds am getting alert message.
In the same way until 90 seconds. If I am getting COStatus as 0 means am showing alert. This alert is go on repeating.
how to achieve this?. Could anyone help me with this
var myTimer : Timer?
var timeController : Bool = true
func myAPICall(){
self.loadingview()
if self.myTimer == nil {
self.myTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.COStatusAPI), userInfo: nil, repeats: self.timeController)
}
}
@objc func COStatusAPI(){
if COStatus == 0{
self.timeController = true
let when = DispatchTime.now() + 90
DispatchQueue.main.asyncAfter(deadline: when) {
self.timeController = false
if self.acceptOrRejectTimer != nil {
self.acceptOrRejectTimer!.invalidate()
self.acceptOrRejectTimer = nil
}
self.hideloadingView()
//showing alert
}
}
if COStatus == 1{
self.timeController = false
if self.acceptOrRejectTimer != nil {
self.acceptOrRejectTimer!.invalidate()
self.acceptOrRejectTimer = nil
}
self.hideloadingview()
//navigating to next view controller
}
}
Upvotes: 2
Views: 4571
Reputation: 285059
DispatchQueue.main.asyncAfter
.Int
counter property with value 18.COStatusAPI()
make the API call.COStatus == 1
invalidate()
the timer and go to the next controller.invalidate()
the timer and show the alert.var myTimer : Timer?
var counter = 0
func myAPICall(){
self.loadingview()
if self.myTimer == nil {
counter = 18
self.myTimer = Timer.scheduledTimer(timeInterval: 5.0,
target: self,
selector: #selector(COStatusAPI),
userInfo: nil,
repeats: true)
}
}
@objc func COStatusAPI(_ timer: Timer) {
// call API
switch COStatus {
case 0:
counter -= 1
if counter == 0 {
timer.invalidate()
self.myTimer = nil
//showing alert
}
case 1:
timer.invalidate()
self.myTimer = nil
//navigating to next view controller
default: break
}
}
Upvotes: 3