-2

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

2 回答 2

0

你不能。您可以注册后台处理,以便为您的应用分配一点时间来做一些工作。但是,您无法控制该时间分配何时到达。它可以像每 20 分钟左右一样频繁,但也可以更长。

于 2020-06-03T00:23:03.663 回答
0

如果要从后台调用 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

于 2020-05-13T09:09:58.647 回答