由于我添加了 WatchConnectivity,我的应用程序在启动时崩溃。我已经简化了应用程序,直到我删除的任何内容也删除了错误。
现在这个最小的应用程序处于一种奇怪的状态,每当我删除完全不相关的东西时,错误就会消失。@AppStorage
例如,如果我用 替换属性@State
,或者如果我选择修饰符的不同变体.fullScreenCover()
,或者如果我删除视图.frame(maxWidth: .infinity, alignment: .leading)
中行上的修饰符,或者如果我用视图的内容ForEach
替换视图,则错误会消失。ForEach
ForEach
我想这个问题是某种竞争条件。如果我发现为什么会发生这种情况,我可以确保错误不会再次随机出现。
要重现,只需在 XCode 中创建一个新的 iOS 应用程序并将其中的所有代码替换为ContentView
:
import SwiftUI
import WatchConnectivity
struct ContentView: View {
@StateObject var connectivity = Connectivity()
@AppStorage("setupKey") var hasBeenSetupBefore: Bool = false
var body: some View {
let sheetBinding = Binding<ActiveSheet?>(
get: {
if !hasBeenSetupBefore {
return ActiveSheet.setup
} else {
return nil
}
},
set: { _ in }
)
Text("Hello World")
.fullScreenCover(
item: sheetBinding,
content: { _ in
WelcomeScreen()
}
)
}
enum ActiveSheet: Identifiable {
case setup, settings
var id: Int {
hashValue
}
}
}
struct WelcomeScreen: View {
var body: some View {
NavigationView {
VStack {
ForEach(features) { feature in
Text("hello")
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
}
let features = [
Feature()
]
}
struct Feature: Identifiable {
var id = UUID()
}
class Connectivity: NSObject, ObservableObject, WCSessionDelegate {
@Published var activationState = WCSessionActivationState.notActivated
override init() {
super.init()
if WCSession.isSupported() {
let session = WCSession.default
session.delegate = self
session.activate()
}
}
func session(
_ session: WCSession,
activationDidCompleteWith activationState: WCSessionActivationState,
error: Error?
) {
DispatchQueue.main.async {
self.activationState = activationState
}
}
func sessionDidBecomeInactive(_ session: WCSession) {}
func sessionDidDeactivate(_ session: WCSession) {}
func updateComplication(with data: [String: Any]) {}
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) {}
}