I’m making an attempt to implement a repeating API name in my iOS app (Swift), and I would like the decision to occur at precisely 00 and half-hour of each hour (e.g., 1:00, 1:30, 2:00, and so on.).
- On launch (when app is in foreground), I wish to make the primary API name to examine if a slot is offered.
- Then, I wish to schedule the API to run at each hour and half-hour mark.
- This must be correct to the clock (not simply each 1800 seconds), so the API ought to hearth precisely at hh:00 and hh:30.
Utilizing this strategy, the API is known as 30–40 occasions per minute inside a single view controller. The API name is triggered from a customized navigation bar (ENavigationBar), which is subclass of UIView.
func scheduleFunctionCall() {
if UIApplication.shared.applicationState == .background { return }
// We examine the physician appointment the primary time to see if it is obtainable.
self.drTimer?.invalidate()
self.drTimer = nil
if !GlobalConstant.appCONSTANT.isDrAppointmentCheckedFirstTime {
checkDrAppointmentAvailable()
} else {
if GlobalConstant.appCONSTANT.roomName != "" {
showNeedHelpDrButton()
} else {
hideNeedHelpDrView()
}
}
// Get the present time
let calendar = Calendar.present
let now = Date()
let minute = calendar.part(.minute, from: now)
let second = calendar.part(.second, from: now)
var fireInSeconds: TimeInterval = 0
if minute < 1 || (minute >= 31 && minute < 32) {
// If it is already at :00 or :30, simply look ahead to the subsequent second alignment
fireInSeconds = TimeInterval(60 - second)
} else if minute < 31 {
fireInSeconds = TimeInterval((31 - minute) * 60 - second)
} else {
fireInSeconds = TimeInterval((61 - minute) * 60 - second)
}
Timer.scheduledTimer(withTimeInterval: fireInSeconds, repeats: false) { _ in
self.checkDrAppointmentAvailable()
// Now arrange the repeating timer each half-hour
self.drTimer = Timer.scheduledTimer(withTimeInterval: 1800, repeats: true) { _ in
self.checkDrAppointmentAvailable()
let nextMinute = minute < 31 ? "00" : "30"
print("Operate known as at (calendar.part(.hour, from: Date())):(nextMinute)")
}
}
}