[英]How to use `.backgroundTask` modifier while still targeting iOS 15?
I'm trying to use the new .backgroundTask modifier announced at WWDC '22 but I can't get the below to compile?我正在尝试使用 WWDC '22 上宣布的新.backgroundTask 修饰符,但我无法编译以下内容? Xcode says
Cannot infer contextual base in reference to member 'appRefresh'
🤔 How can I do this? Xcode 说
Cannot infer contextual base in reference to member 'appRefresh'
🤔 我该怎么做?
import SwiftUI
import Foundation
import BackgroundTasks
var body: some Scene {
WindowGroup {
if #available(iOS 16, *) {
AppRootView()
.backgroundTask(.appRefresh("refreshAllData")) {
refreshData()
}
} else {
AppRootView()
}
}
}
Edit: as agentBilly said .backgroundTask is a scene modifier, so should look like this but I'm still unsure how to check for iOS 16 availability?编辑:正如 agentBilly 所说 .backgroundTask 是一个场景修饰符,所以应该看起来像这样,但我仍然不确定如何检查 iOS 16 的可用性?
import SwiftUI
import Foundation
import BackgroundTasks
@main
struct myApp: App {
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
AppRootView()
}
.backgroundTask(.appRefresh("refreshAllData")) {
refreshAllData()
}
}
We cannot use condition right in scene body, because SceneBuilder
does not support conditional expression, so a solution is to have completely different apps loaded depending on availability.我们不能在场景主体中使用条件,因为
SceneBuilder
不支持条件表达式,所以解决方案是根据可用性加载完全不同的应用程序。
Simplified code to have less lines:简化代码以减少行数:
struct AppScene: Scene {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
@available(iOS 16, *)
struct RefreshingAppScene: Scene {
var body: some Scene {
WindowGroup {
ContentView()
}
.backgroundTask(.appRefresh("refreshAllData")) {
refreshAllData()
}
}
}
@main
struct AppLoader {
static func main() {
if #available(iOS 16, *) { // << conditional availability !!
New_iOSApp.main()
} else {
Old_iOSApp.main()
}
}
}
@available (iOS 16, *)
struct New_iOSApp: App {
var body: some Scene {
RefreshingAppScene()
}
}
struct Old_iOSApp: App {
var body: some Scene {
AppScene()
}
}
Tested with Xcode 14b3 / iOS 16使用 Xcode 14b3 / iOS 16 测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.