Braver Chiang
Braver Chiang

Reputation: 381

How to refresh swiftUI view automatically after Core Data updating in background?

How to refresh swiftUI view automatically after Core Data updating in background, without onAppear method being called?

struct Page1: View {

@FetchRequest(entity: Word.entity(), sortDescriptors: [])
var wordsFromCoreData: FetchedResults<Word>

@State var isPresenting = false


var body: some View {

    NavigationView{
        VStack{
            NavigationLink(destination: Page2()){
                Text("Add")

            }
            List(wordsFromCoreData, id: \.self){item in

                WordRowView(word:item)

            }.navigationBarTitle(Text("English Words"))
        }
    }
}
}

Yes, I think @FetchRequest will help me reload the data automaticly after my Page1 appear

But, If I use NavigationLink or .sheet to get to Page2, swift won't call onAppear I think.

So, If I go to Page2, do some Core Data thing like fetching image from Internet, then I go back to Page1, it never show the data, but the data has actually existed in My Core Data. So, it means Page1 doesn't refresh the data in this situation.

Another situation works fine, for example, I set Page2 as another TabView instead of NavigationLink(A Detail View), when I go back to Page1, the view has been refreshed.

But I prefer NavigationLink to get my work done. So, Is There any way to refresh swiftUI view automatically after Core Data updating in background?

Upvotes: 10

Views: 2052

Answers (1)

Riley Usagi
Riley Usagi

Reputation: 47

CoreData have built in Notifications.

Look this article for details.

In your Views you can use .onReceive modificator to receive this notifications and update View.

Upvotes: 1

Related Questions