即使我在ios swift4中杀死了应用程序,如何继续执行后台任务

时间:2018-08-11 09:56:38

标签: background-process nsurlsession uibackgroundtask applicationwillterminate

请检查我在下面执行的后台执行代码,即使我终止了该应用程序,我也需要继续运行计时器n次。

var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid

override func viewDidLoad() {
    super.viewDidLoad()

    if isBgRunnerOn {
      NotificationCenter.default.addObserver(self, selector: #selector(reinstateBackgroundTask), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
    }
}

@objc func updateLabel() {
    seconds += 1
    timerLabel.text = "\(seconds)\(" Sec")"
    print(seconds)
    if UIApplication.shared.backgroundTimeRemaining < 5 {
        reinstateBackgroundTask()
    }
}

func runTimer() {
    if isBgRunnerOn {
        registerBackgroundTask()
    }
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateLabel), userInfo: nil, repeats: true)
    isTimerRunning = true
}

func registerBackgroundTask() {
    backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
        // after minimum time duration of background session (3 min).
        self?.reinstateBackgroundTask()
    }
    assert(backgroundTask != UIBackgroundTaskInvalid)
}

func endBackgroundTask() {
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

@objc func reinstateBackgroundTask() {
    if timer != nil && (backgroundTask == UIBackgroundTaskInvalid) {
        registerBackgroundTask()
    }
}

如何在应用终止状态下执行任务?我该怎么办?

0 个答案:

没有答案