Share Realm Data with WatchOS

后端 未结 2 2075
小鲜肉
小鲜肉 2021-01-13 04:07

In my project I want to use one Realm Database with my iOS 10 application and my watchOs 3 application at the same time. So what I did was adding the frameworks to the embed

相关标签:
2条回答
  • 2021-01-13 04:37

    Update: Okay, thanks to chrisamanse's heads-up, I did some more research on this.

    It turns out that App Groups are no longer possible on watchOS 2. Watch apps no longer run as extensions on the phone; they are now two isolated processes without any shared resources.

    As such, this means it will be necessary to maintain a separate Realm file on both the watch and the phone and communicate any changes made to either through the WatchConnectivity framework.


    Original: iOS applications and extensions (both Today widgets and watchOS apps) need to be considered as two wholly separate entities in their own separate containers. By default, an extension cannot access any files inside the container of its parent application. If you're saving a Realm file to the default path (i.e., the 'Documents' folder), there's no way for the watchOS app to access it from there.

    Thankfully, it's possible to use the 'App Groups' feature of iOS to specify a shared folder that both the parent iOS app and the watchOS app can access, and can both read and write any Realm files that are in there.

    Once you've enabled the App Groups entitlement in your app, it's just a matter of setting your Realm file's location to point to that location.

    let sharedContainerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.my.appgroups.bundleid")!
    let realmURL = sharedContainerURL.appendingPathComponent("SharedRealm.realm")
    
    let realmConfiguration = Realm.Configuration()
    realmConfiguration.fileURL = realmURL
    let realm = try! Realm(configuration: realmConfiguration)
    

    There's a tutorial on the Realm website that explains how to make this work in more detail, however the API and Swift version are out of date at this point.

    0 讨论(0)
  • 2021-01-13 04:43

    For Swift 3

    I used the following code to share Realm db between app and app extension:

    let sharedDirectory: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.your.app")! as URL
    let sharedRealmURL = sharedDirectory.appendingPathComponent("db.realm")
    Realm.Configuration.defaultConfiguration = Realm.Configuration(fileURL: sharedRealmURL)
    
    0 讨论(0)
提交回复
热议问题