Reputation: 41
I want to create an app as when a particular time comes it calls an API. I have done in it the foreground, but when the app is in the background, it is not executing. How can I solve the issue?
My code is below:
@objc func runCode() {
print("runcode")
timeLabel.text = "Pls select time"
}
@IBAction func dateChange(_ sender: UIDatePicker) {
if (timer != nil) {
timer.invalidate()
}
print("print \(sender.date)")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm E, d MMM y"
let somedateString = dateFormatter.string(from: sender.date)
print(somedateString)
timer = Timer(fireAt: sender.date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: .common)
timeLabel.text = "api will trigger at \(somedateString)"
}
@IBAction func switchAction(_ sender: UISwitch) {
if stateSwitch.isOn {
date.isHidden = false
print("The Switch is on")
timeLabel.text = "Pls select time"
} else {
date.isHidden = true
if (timer != nil) {
timer.invalidate()
}
timeLabel.text = "Timer not activated"
print("Timer not activated")
}
}
Upvotes: -2
Views: 1080
Reputation: 267
You can't. You can register for background processing so that your app is allotted a little time in which to do some work. You cannot control when that time allotment will arrive though. It can be as frequent as every 20 minutes or so but it can also be much longer.
Upvotes: 0
Reputation: 881
If you want to call api from background, the thread must be in background first. Morever, you can register background fetch : https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/updating_your_app_with_background_app_refresh
Upvotes: 0