Share Realm Data with WatchOS

白昼怎懂夜的黑 提交于 2019-12-01 04:20:11

问题


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 embedded binaries for the three different targets. This happened to work very well but the watchKit extension doesn't seem to recognize the objects that I created within the iOS environment. How is it possible to have a shared Realm Database between those two devices?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/39644579/share-realm-data-with-watchos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!