SwiftUI中如何实现后台任务?BGTaskScheduler注册代码应放在项目哪里?
后台任务注册代码的放置位置
这段BGTaskScheduler注册代码需要放在应用冷启动完成的最早阶段,不能延迟到任意视图加载后才调用,否则后台被系统唤醒时会无法触发对应的任务逻辑,SwiftUI项目有两种主流适配方案:
方案1:直接放在App结构体的初始化方法中(更推荐)
@main struct YourApp: App { init() { // 在此处插入后台任务注册代码 BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.apple-samplecode.ColorFeed.refresh", using: nil) { task in handleAppRefresh(task: task as! BGAppRefreshTask) } } var body: some Scene { WindowGroup { ContentView() } } // 后台任务逻辑实现 private func handleAppRefresh(task: BGAppRefreshTask) { // 补充你的刷新逻辑、任务过期处理等代码 } }
方案2:通过AppDelegate适配(需要监听系统启动回调时用)
- 第一步:创建自定义AppDelegate类,在启动回调中注册
class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // 在此处插入后台任务注册代码 BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.apple-samplecode.ColorFeed.refresh", using: nil) { task in self.handleAppRefresh(task: task as! BGAppRefreshTask) } return true } private func handleAppRefresh(task: BGAppRefreshTask) { // 补充你的刷新逻辑、任务过期处理等代码 } }
- 第二步:在App结构体中关联自定义AppDelegate
@main struct YourApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } }
注意:除了放置位置正确外,你还需要提前在项目的Signing & Capabilities中添加Background Modes能力,勾选Background fetch选项,同时在Info.plist中注册对应的任务标识。
内容的提问来源于stack exchange,提问作者lostForAWHile
相关产品推荐
相关产品推荐

