微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在WidgetKit中显示核心数据中的数据

如何解决如何在WidgetKit中显示核心数据中的数据

这是我的代码,我试图从WidgetKit中的Core Data中列出存储的数据,但根本没有显示。我已经创建了应用程序组,并且数据在预览中显示,但是当我们将小部件添加到主屏幕时,没有任何显示。我不确定自己做的方法是否正确。

在WidgetKit中列出核心数据记录的最佳方法是什么?

import WidgetKit
import SwiftUI
import CoreData

// MARK: For Core Data

public extension URL {
    /// Returns a URL for the given app group and database pointing to the sqlite database.
    static func storeURL(for appGroup: String,databaseName: String) -> URL {
        guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
            fatalError("Shared file container Could not be created.")
        }

        return fileContainer.appendingPathComponent("\(databaseName).sqlite")
    }
}

var managedobjectContext: NSManagedobjectContext {
    return persistentContainer.viewContext
}

var workingContext: NSManagedobjectContext {
    let context = NSManagedobjectContext(concurrencyType: .privateQueueConcurrencyType)
    context.parent = managedobjectContext
    return context
}

var persistentContainer: NSPersistentCloudKitContainer = {
    let container = NSPersistentCloudKitContainer(name: "Countdowns")

    let storeURL = URL.storeURL(for: "group.app-group-countdowns",databaseName: "Countdowns")
    let description = NSPersistentStoreDescription(url: storeURL)

    container.loadPersistentStores(completionHandler: { storeDescription,error in
        if let error = error as NSError? {
            print(error)
        }
    })

    container.viewContext.automaticallyMergesChangesFromParent = true
    container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy

    return container
}()

// MARK: For Widget

struct Provider: TimelineProvider {
    var moc = managedobjectContext

    init(context : NSManagedobjectContext) {
        self.moc = context
    }

    func placeholder(in context: Context) -> SimpleEntry {
        return SimpleEntry(date: Date())
    }

    func getSnapshot(in context: Context,completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date())
        return completion(entry)
    }

    func getTimeline(in context: Context,completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []

        let currentDate = Date()
        let entryDate = Calendar.current.date(byAdding: .minute,value: 1,to: currentDate)!
        let entry = SimpleEntry(date: entryDate)
        entries.append(entry)

        let timeline = Timeline(entries: entries,policy: .atEnd)
        completion(timeline)
    }
}

struct SimpleEntry: TimelineEntry {
    let date: Date
}

struct CountdownsWidgetEntryView : View {
    var entry: Provider.Entry

    @FetchRequest(entity: Countdown.entity(),sortDescriptors: []) var countdowns: FetchedResults<Countdown>

    var body: some View {
        return (
            vstack {
                ForEach(countdowns,id: \.self) { (memoryItem: Countdown) in
                    Text(memoryItem.title ?? "Default title")
                }.environment(\.managedobjectContext,managedobjectContext)
                Text(entry.date,style: .time)
            }
        )
    }
}

@main
struct CountdownsWidget: Widget {
    let kind: String = "CountdownsWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind,provider: Provider(context: managedobjectContext)) { entry in
            CountdownsWidgetEntryView(entry: entry)
                .environment(\.managedobjectContext,managedobjectContext)
        }
        .configurationdisplayName("My Widget")
        .description("This is an example widget.")
    }
}

struct CountdownsWidget_Previews: PreviewProvider {
    static var previews: some View {
        CountdownsWidgetEntryView(entry: SimpleEntry(date: Date()))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}

解决方法

只需在托管对象上下文上执行调用,并且由于您使用的是私有上下文,请确保调用performBlock。

Table B

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。