iosswiftrealmwatchkitwatchos-3

Share Realm Data with WatchOS


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?


Solution

  • 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.