【问题标题】:how to fetch coredata in widget如何在小部件中获取核心数据
【发布时间】:2021-11-02 20:13:30
【问题描述】:

我正在尝试在小部件中获取核心数据。

在 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 = 试试 context.fetch(request) as? [实体]

发生错误。

错误是类型“Provider.Context”(又名“TimelineProviderContext”)的值没有成员“fetch”*

请帮帮我!!

【问题讨论】:

    标签: ios swift widget


    【解决方案1】:

    您的context 是在函数参数中定义的,因此它不是CoreData 上下文,而是时间轴的TimelineProviderContext

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

    yourResult = try moc.fetch(request) as? [Entity]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      相关资源
      最近更新 更多