Reputation: 21
I am having the following fatal error:
SwiftUI Fatal error: No ObservableObject of type “ ” found and @EnvironmentObject error: may be missing as an ancestor of this view」 is occured.
Xcode version:
Xcode:12.1 and Core Bluetooth
My codes are as bellow:
ble.swift
import CoreBluetooth
・・・
class BLEConnection:NSObject, CBPeripheralDelegate,CBCentralManagerDelegate,ObservableObject
{
@EnvironmentObject var GS: GlobalStatus
・・・・
func startCentralManager()
{
//Process of start BLE Scan
}
public func centralManager(・・・) ← Scanned Peripheral
{
let localName:String
if(localName == GS.beaconid) ← ★★★Fatal Error Occured this point.★★★
{
・・・・
}
・・・・
GlobalStatus.swift
class GlobalStatus: ObservableObject
{
@Published var beaconid = "ID001"
}
ProjectName.swift
@main
struct ProjectName: App
{
let persistenceController = PersistenceController.shared
var body: some Scene
{
WindowGroup
{
ContentView()
.environment(\.managedObjectContext,persistenceController.container.viewContext)
.environmentObject(GlobalStatus())
}
}
}
ContentView.swift
・・・
struct ContentView: View
{
@ObservedObject var bke = BLEConnection()
var body: some VIew
{
NavigationView
{
Text("Test")
}.onAppear(perform: ble.startCentralManager)
}
}
How can I resolve this problem? Thanks in advance.
Upvotes: 2
Views: 1382
Reputation: 258345
@EnvironmentObject
is for SwiftUI view. In class just use regular property:
class BLEConnection:NSObject, CBPeripheralDelegate,CBCentralManagerDelegate,ObservableObject
{
var GS: GlobalStatus!
// ...
}
and in your view just inject one into another (as one of approach)
struct ContentView: View
{
@EnvironmentObject var GS: GlobalStatus
@ObservedObject var bke = BLEConnection()
var body: some VIew
{
NavigationView
{
Text("Test")
}.onAppear {
ble.GS = self.GS
ble.startCentralManager()
}
}
}
Upvotes: 1