为什么我的应用程序不在后台模式下工作,而在前台模式下工作



我想创建一个应用程序,因为当特定时间到来时,它会调用API。我在前台做过,但当应用程序在后台时,它不会执行。我该如何解决这个问题?

我的代码如下:

@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")
}
}

如果要从后台调用api,线程必须先在后台。此外,您还可以注册后台获取: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

你不能。你可以注册进行后台处理,这样你的应用程序就有一点时间来做一些工作。不过,您无法控制时间分配何时到达。它可能每20分钟左右发生一次,但也可能更长。

最新更新