如何获取coredata在小部件

2022-01-28 08:59:05 标签 iosswiftwidget

我试图获取coredata在小部件。

在viewcontroller中,我成功获取coredata,但在widget。swift中,我不能获得我的核心数据。

这是我的代码

widget。swift

func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: <My GroupId>)!
        let storeURL = containerURL.appendingPathComponent("DataModel.sqlite")
        let description = NSPersistentStoreDescription(url: storeURL)
        let container = NSPersistentContainer(name: "Entity")
        container.persistentStoreDescriptions = [description]
        container.loadPersistentStores { description, error in
            if let error = error {
                fatalError("Unable to load persistent stores: \(error)")
            } }
        
        var yourResult : [Entity]?
        let moc = CoreDataStack.shared.managedObjectContext
        let predicate = NSPredicate(format: "name == %@", "test")
        let request = NSFetchRequest<Entity>(entityName: "Entity")
        let result = try? moc.fetch(request)
        request.predicate = NSPredicate(format: "attribute1 == %@", "test")
                do {
                    yourResult = try context.fetch(request) as? [Entity]
                    completion(yourResult)
                } catch let error as NSError{
                    print(error.localizedDescription)
                }
        
        var entries: [SimpleEntry] = []
        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
            let entry = SimpleEntry(date: entryDate, configuration: configuration)
            entries.append(entry)
        }
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }

这条线

yourResult = try context。fetch(request) as?(实体)

发生错误。

error是“Provider”类型的值。Context'(又名'TimelineProviderContext')没有成员'fetch'*

请帮助我! !

# # #你context is defined是在函数参数中定义的,因此它不是CoreData上下文,而是TimelineProviderContext for the timeline.

时间轴。

在添加谓词之前,尝试使用以下代码获取数据:

yourResult = try moc.fetch(request) as? [Entity]
阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码