首页 > 解决方案 > '没有为具有标识符的任务注册启动处理程序......'(Swift)

问题描述

我有这段代码是文本到语音的,最后它会打开带有指定链接的默认浏览器

func speak(text : String, callback : (() -> Void)? = nil, link: String) {
        let state = returnState()
        print(state)
        if state == .quiet {
            do {

                self.state = .speaking
                try audioSession.setCategory(AVAudioSession.Category.playback)
                try audioSession.setMode(AVAudioSession.Mode.default)
                try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
                let utterance = AVSpeechUtterance(string: text)
                utterance.voice = AVSpeechSynthesisVoice(language: language)
                synthesizer.speak(utterance)
                self.showWaveform()
                self.callbackSpeak = callback
                let url = URL(string: link)!
                let seconds = 4.0
                DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
                    UIApplication.shared.open(url)
                }

            } catch {
                print("audioSession properties weren't set because of an error.")
            }
        }
    }

我不断收到此错误:

'No launch handler registered for task with identifier com.maps.fetch.activities'

我检查了权限,在“允许的后台任务调度程序标识符”下,我确实有“com.maps.fetch.activities”。

在此处输入图像描述

我想我必须使用该标识符注册一个任务,但我不确定那是什么以及我应该在哪里做。你能帮我解决这个问题吗?

标签: swiftbackgroundtask

解决方案


那是因为你没有打电话BGTaskScheduler.shared.registerdidFinishLaunchingWithOptions

if ( !BGTaskScheduler.shared.register(forTaskWithIdentifier: BackupTask.identifier,
                    using: nil) { task in
    BackupTask.handleProcess(task as? BGProcessingTask)
} ){
    logHelper.w("BackupTask register failed.")
}

并将其放入applicationDidEnterBackground.

if #available(iOS 13.0, *) {
    BackupTask.scheduleProcessing()
}

这是scheduleProcessing看起来的样子。

@available(iOS 13, *)
static func scheduleProcessing() {
    let logHelper = LogHelper(subsystem: "TimeMachineTask", category: "scheduleProcessing")

    let request = BGAppRefreshTaskRequest(identifier: TimeMachineTask.identifier)
    // Fetch no earlier than 5 minutes from now
    request.earliestBeginDate = Date(timeIntervalSinceNow:  60 * 15)
    do {
        try BGTaskScheduler.shared.submit(request)
        logHelper.i("Submit new request.")
    } catch {
        logHelper.e("Could not schedule app refresh: %@", error: error)
    }
}

BGTaskScheduler.shared.register告诉iOS在启动后台任务后要做什么,这是您缺少的“启动处理程序”。 BackupTask.scheduleProcessing是它实际安排工作的地方。

您可以下载他们的示例项目以查看它如何与OperationQueue. https://developer.apple.com/documentation/backgroundtasks/refreshing_and_maintaining_your_app_using_background_tasks


推荐阅读