如何在应用和键盘扩展之间共享Realm DataBase?

时间:2018-02-09 19:49:30

标签: swift realm ios-keyboard-extension

我尝试使用键盘扩展程序和应用程序进行读取,编写相同的realm文件,我的代码是:

DatabaseHelper

class DataBaseHelper
{
    static let DB_VERSION: UInt64 = 1
    //MARK: Creates Methods
    class func createOrUpdateEmoji(_ emoji: Emoji)
    {
        do {
            let realm = try Realm()
            realm.refresh()
            try realm.write {
                realm.create(Emoji.self, value: emoji, update: true)
                debugPrint("--->Emoji added or updated: \(emoji.id),\(emoji.name)")
            }

        } catch {
            debugPrint("Error creating or updating Emoji")
        }
    }

    //MARK: Creates Methods
    class func getEmojis() -> Results<Emoji>?
    {
        do {
            let realm = try Realm()
            return realm.objects(Emoji.self).sorted(byKeyPath: "id", ascending: true)
        } catch {
            return nil
        }
    }

    //MARK: Migrations
    class func DataBaseConnectOrUpdate()
    {
        let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
            if oldSchemaVersion < 1
            {
            }
            debugPrint("->oldSchemaVersion:\(oldSchemaVersion)")
            debugPrint("Migration complete.")
        }

        var config = Realm.Configuration(schemaVersion: DB_VERSION, migrationBlock: migrationBlock)
        config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.my.extension")!.appendingPathComponent("database.realm")

        Realm.Configuration.defaultConfiguration = config
        let realm = try! Realm()
        debugPrint("--->Path to realm file:\(String(describing: Realm.Configuration.defaultConfiguration.fileURL?.path))")
        try! FileManager.default.setAttributes([FileAttributeKey.protectionKey:kCFURLFileProtectionNone], ofItemAtPath: (realm.configuration.fileURL?.path)!)
    }
}

模型

import UIKit
import RealmSwift
import SwiftyJSON

class Emoji: Object
{
    @objc dynamic var id = 0
    @objc dynamic var name = ""
    @objc dynamic var code = ""
    @objc dynamic var image = ""

    override static func primaryKey() -> String
    {
        return "id"
    }

    static func fromJson(_ json:JSON) -> Emoji
    {
        let emoji = Emoji()
        emoji.id = json["id"].intValue
        emoji.name = json["name"].stringValue
        emoji.code = json["code"].stringValue
        emoji.image = json["image"].stringValue
        return emoji
    }
}

的AppDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        DataBaseHelper.DataBaseConnectOrUpdate()
        return true
    }

App ViewController

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.syncEmojis()
    }

键盘扩展ViewController

var emojisFromDataBase:Results<Emoji>? = nil
override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        DataBaseHelper.DataBaseConnectOrUpdate()
        self.emojisFromDataBase = DataBaseHelper.getEmojis()
        for emoji in emojisFromDataBase!
        {
            debugPrint("emoji:\(emoji.name)")
        }
    }

因此,当我在iOS模拟器上运行时,在两种情况下都能正常运行:

iOS模拟器:

应用

"--->Path to realm file:Optional(\"/Users/dmostajo/Library/Developer/CoreSimulator/Devices/LARGE-CODE/data/Containers/Shared/AppGroup/LARGE-CODE-2/database.realm\")"
"--->Emoji added or updated: 1,Satan"
"--->Emoji added or updated: 2,Cthulhu"
"--->Emoji added or updated: 3,Hellboy"
"--->Emoji added or updated: 4,Mercyful Fate"
"--->Emoji added or updated: 5,God"
"--->Emoji added or updated: 6,Virgin Mary"

键盘扩展名:

"--->Path to realm file:Optional(\"/Users/dmostajo/Library/Developer/CoreSimulator/Devices/LARGE-CODE/data/Containers/Shared/AppGroup/LARGE-CODE-2/database.realm\")"
"emoji:Satan"
"emoji:Cthulhu"
"emoji:Hellboy"
"emoji:Mercyful Fate"
"emoji:God"
"emoji:Virgin Mary"
Real Device iPhone SE上的

应用

"--->Path to realm file:Optional(\"/private/var/mobile/Containers/Shared/AppGroup/LARGE-CODE/database.realm")"
"--->Emoji added or updated: 1,Satan"
"--->Emoji added or updated: 2,Cthulhu"
"--->Emoji added or updated: 3,Hellboy"
"--->Emoji added or updated: 4,Mercyful Fate"
"--->Emoji added or updated: 5,God"
"--->Emoji added or updated: 6,Virgin Mary"
键盘扩展名

CRASH

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=2
"Unable to open a realm at path '/private/var/mobile/Containers/Shared/AppGroup/LARGE-CODE/database.realm.lock': open() failed: Operation not permitted."
UserInfo={Error Code=2, NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/LARGE-CODE/database.realm.lock,
Underlying=open("/private/var/mobile/Containers/Shared/AppGroup/LARGE-CODE/database.realm.lock") failed: Operation not permitted,
NSLocalizedDescription=Unable to open a realm at path '/private/var/mobile/Containers/Shared/AppGroup/LARGE-CODE/database.realm.lock': open() failed: Operation not permitted.}: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.74.1/src/swift/stdlib/public/core/ErrorType.swift, line 181

我使用RealmSwift 3.1.1,Xcode 9.2,iOS 11.1.2,Swift 4,所以有什么帮助吗?我错过了什么?,我该如何解决?

谢谢!

0 个答案:

没有答案