gpt4 book ai didi

ios - 后台任务不在 Swift 中调用类

转载 作者:可可西里 更新时间:2023-11-01 00:39:02 31 4
gpt4 key购买 nike

我有一个后台任务,它应该返回一组类(class),然后将这些类(class)发送到 Apple Watch。我通过 WatchConnectivitydidReceiveMessage 中调用任务。

后台任务需要执行一些操作,例如打开领域数据库、查询结果和访问文档目录,然后再将响应返回给类(class)字典。当 watch 输出其获取类(class)数据时,逻辑似乎有效。问题是我不认为后台任务实际上是在调用方法 getWatchCourses()

DispatchQueue.global().async {

var foundCourses = [[String : Any]]()
let application = UIApplication.shared
backgroundTask = application.beginBackgroundTask(withName: "app.test.getCourses") {
let watchModel = WatchCourseModel()
let courses = watchModel.getWatchCourses()
print("Courses: \(courses)")
foundCourses.append(contentsOf: courses)
}
replyHandler(["response": foundCourses])
application.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}

如果 getWatchCourses() 结果是硬编码的,这也不起作用。应用程序可以在后台执行此逻辑还是应该运行?

It's also worth pointing out that nowhere online has this documented, They always refer to sending simple text responses back to the watch, not something processor intensive :(

谢谢

最佳答案

您在用于清理的尾随闭包中进行操作。还有更多事情是您在后台任务开始后立即结束,因此您的闭包永远不会调用。

这是后台任务如何工作的工作示例

 var backgroundTaskIdentifier:UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
var updateTimer: Timer?

现在,当您开始运行示例运行计时器时

  updateTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self,
selector: #selector(calculateNextNumber), userInfo: nil, repeats: true)
// register background task
beginBackgroundTask()

当你结束计时器时,结束后台任务;应该总是无误地结束后台任务

func beginBackgroundTask () {
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { [weak self] in
self?.endBackgroundTask() // It will call to cleanup
})
assert(backgroundTaskIdentifier != UIBackgroundTaskInvalid)
}

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

所以在你的情况下

  • 注册后台任务
  • 查询您的数据库(执行您的所有操作)
  • 当你完成通话结束后台任务

注意:还要注意苹果给你的后台任务执行时间限制

编辑

确保您已从项目设置中启用后台功能

试试看

    beginBackgroundTask()

let watchModel = WatchCourseModel()
let courses = watchModel.getWatchCourses()
print("Courses: \(courses)")
foundCourses.append(contentsOf: courses)
endBackgroundTask()

关于ios - 后台任务不在 Swift 中调用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51302588/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com