我想创建一个应用程序,当一个特定的时间,它调用一个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")
}
}
你不能这样做。 你可以注册后台处理,这样你的应用就会被分配到一点时间来做一些工作。 不过你无法控制该时间分配何时到来。 它可以频繁到每20分钟左右,但也可以更长。