Fetch data from CoreData for iOS 14 widget

前端 未结 1 2002
逝去的感伤
逝去的感伤 2020-12-15 13:37

I want to display data fetched from Core Data in a widget. But @FetchRequest doesn’t work on widgets.

As I understand, we have to create an app group and

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 14:15

    First you need to create an AppGroup which will be used to create a Core Data Persistent Container (here is a good explanation how to do it)

    Then you need to create your own CoreData stack (an example can be found when you create a new empty project with CoreData enabled).

    • Accessing Core Data Stack in MVVM application

    Assuming you have already created your Core Data model (here called DataModel), you now need to set the container url to your custom shared container location:

    • Share data between main App and Widget in SwiftUI for iOS 14
    let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: )!
    let storeURL = containerURL.appendingPathComponent("DataModel.sqlite")
    let description = NSPersistentStoreDescription(url: storeURL)
    
    let container = NSPersistentContainer(name: "DataModel")
    container.persistentStoreDescriptions = [description]
    container.loadPersistentStores { ... }
    

    Now you can get the managedObjectContext from your shared Persistent Container:

    let moc = CoreDataStack.shared.managedObjectContext
    

    and perform a fetch request with it (more information here)

    let predicate = NSPredicate(format: "attribute1 == %@", "test")
    let request = NSFetchRequest(entityName: "SomeItem")
    let result = try moc.fetch(request)
    

    Apart from all the links above I recommend you also read this tutorial about Core Data:

    • Core Data with SwiftUI Tutorial: Getting Started

    Here is a GitHub repository with different Widget examples including the Core Data Widget.

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