my first view can get all the data from API request, then opened second view to change the API request data, it crashed.
below is the error
Fatal error:
if you are using sheet ore navigation you have to pass the environment Object maybe its a bug of swiftUI but it works for me in Xcode 11.5:
.sheet(isPresented: $show){
mySheetView().environmentObject(self.myEnviromentObject)
}
This problem seems to be cause by using two instances of NetworkManager
in your code.
If you add this line to the NetworkManager
:
final class NetworkManager: … {
static let shared = NetworkManager()
}
And then update the references in your two views like this:
struct EarthQuakeList: … {
@ObservedObject var networkManager = NetworkManager.shared
…
}
struct EditPage: … {
@ObservedObject var networkManager = NetworkManager.shared
…
}
This will make sure both views use the exact same object to access the information. By using the same object, updates in one view will cause the other view to be updated as well.
Once this works, I recommend to play around with .environmentObject()
(example) in SwiftUI as this would allow for sharing the same instance of these service types across your application.
Good luck with your project!
The whole issue is very easy to fix just add self.networkManager @ EarthQuakeList.swift
.sheet(isPresented: $showEditPage) {
return EditPage().environmentObject(self.networkManager)
I got the reason and inspired from article: https://github.com/peterfriese/Swift-EnvironmentObject-Demo