首页 > 解决方案 > 如何从 IOS 小部件中的领域数据库中获取数据?迅速

问题描述

我有一个当前正在运行的应用程序的现有领域数据库。

我想从数据库中获取数据以显示在小部件中。但是,我收到错误“在范围内找不到类型'项目'。它拼写正确。

import WidgetKit
import SwiftUI
import Intents
import RealmSwift

struct Provider: IntentTimelineProvider {

    let realm = try! Realm()
    var todoItems: Results<Item>?         //cannot find type 'Item' in scope

我已经为这两个目标安装了领域 swift,并设置了一个应用程序组。我还尝试了以下代码:Share Realm Data with WatchOS以及 Swift 5 的更新版本。

这是数据模型的主应用程序目标中的代码:

import Foundation
import RealmSwift

class Item: Object {
    @objc dynamic var title: String = ""
    @objc dynamic var done: Bool = false
    @objc dynamic var dateCreated: Date?
    var parentCategory = LinkingObjects(fromType: Category.self, property: "items")
}

这是应用程序委托

import UIKit
import RealmSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //MARK: Realm Location Setup - Commented out because it didn't work :(
        
//        if var directory: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.lachlanosborne.countdownwidget") {
//        directory.appendPathComponent("db.realm", isDirectory: true)
//        let config = Realm.Configuration(fileURL: directory, schemaVersion: 1)
//        Realm.Configuration.defaultConfiguration = config
//    }
        
        //MARK: Prints
        //print(Realm.Configuration(fileURL: sharedRealmURL))
        print("app running")
        
        //MARK: Realm Setup
        do {
            _ = try Realm()
        } catch {
            print("Error creating realm")
        }
        
        return true
    }

}

标签: iosswiftwidgetrealm

解决方案


推荐阅读