我想创建一个应用程序,因为它会在特定时间到来时调用 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")
}
}