Search code examples
iosswiftswiftuiglobal-variableslaunch

SwiftUI global var and func at launch


I have this func that parses a json. Then I use the data for that to populate a bunch of UI slot. The problem is it's a big json (if 10.1MB is big) and it takes 5-8 seconds to load. At app launch that's no big deal, but right now it' reprising that data every time.

Right now I just have this mode were each struct view starts with:

var results = [ScryfallCard]()

.onApear {
    results = func()
}

func() -> [ScryfallCard]

I can't find for the life of me find out how to make a global variable, assign it the var globleResults = func() so my app loads all that data upfront and doesn't take 5 second to load each view.


Solution

  • In order for your view to update the results, you need to make turn your results results into @State var results: [ScryfallCard] = []

    Then with your function that deals with the JSON, no matter how long it takes to process, it should update the view once the results = func() is finished.

    Avoid using global variables and aim for creating different components to encapsulate the variables.

    You would have something like this

    class NetworkRequester: ObservableObject {
    
        @Published var results: [String] = []
    
        var cancellable: AnyCancellable?
    
        func getResults() {
            cancellable = URLSession.shared.dataTaskPublisher(for: URL(fileURLWithPath: "path-to-JSON")!)
                .map({ $0.data })
                .decode(type: [ScryfallCard].self, decoder: JSONDecoder())
                .sink(receiveCompletion: { result in
                    switch result {
                        case .failure(let error):
                        print(error)
                        case .finished:
                        break
                    }
                }) { newResults in
                    self.results = newResults
            }
        }
    }
    

    The link suggested in the comment is a useful resource to learn more about how to deal with rendering data.