SwiftUI @EnvironmentObject error: may be missing as an ancestor of this view

后端 未结 3 733
Happy的楠姐
Happy的楠姐 2021-02-14 19:55

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:          


        
相关标签:
3条回答
  • 2021-02-14 20:27

    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)
    }
    
    0 讨论(0)
  • 2021-02-14 20:28

    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!

    0 讨论(0)
  • 2021-02-14 20:32

    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

    0 讨论(0)
提交回复
热议问题