-2

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")
    }
}
TylerP
  • 9,600
  • 4
  • 39
  • 43
project ed500
  • 41
  • 1
  • 8
  • 1
    Shortly after your app moves to the background it is suspended. There are specific background execution modes on iOS for functions such as location or playing audio, but general code does not continue executing – Paulw11 May 13 '20 at 06:07

2 Answers2

0

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

King.lbt
  • 843
  • 5
  • 15
0

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.

Wayne Henderson
  • 237
  • 3
  • 9