Search code examples
iosswiftdatabasemobilerealm

Using Realm Mobile Platform with photos


We have a mobile application that currently uses a Realm database in conjunction with photos that are stored in the device’s document folder.

We are looking for a way to allow our users to use the app and share data between different devices are were very interested in the new Realm Mobile Platform. One thing we can’t quite figure out though, is how it would work with the photos. Would we need to manually synch those between devices through another service? Or is there a way to make it work with Realm Mobile Platform? Any ideas of how we could make this work would be greatly appreciated.


Solution

  • Storing the photos in the database would work, but might increase the size by a lot. I imagine you also want to preserve offline capabilities - e.g. if a user adds an image while offline, they'll expect that image to eventually sync.

    One solution would be to have a per-device realm (i.e. give it a unique name to avoid syncing with anything but the server) that could be used as an image upload queue with a single class (pseudocode):

    class Image : RealmObject {
        byte[] Data
    
        // Other properties to map this image to whatever
        // object it belongs to.
    }
    

    Then, your objects with images will look like

    class ObjectWithImage : RealmObject {
        string ImageUrl
    
        // Other properties
    }
    

    So now, when you add a new ObjectWithImage, you'll add a corresponding Image object to the image Realm. Then, on the server, you can listen for changes on the image Realm (requires at least Professional edition) and when a new Image gets synchronized, you can upload the data to AWS S3/Azure blob/other hosting, update the corresponding ObjectWithImage's ImageUrl, and delete the processed Image object. Then on the device you can use an image caching library, e.g. SDWebImage to download the image from the url and store it locally for faster retrieval next time.

    The benefits of this solution are:

    • The shared realm will only contain url's, reducing both storage and bandwidth requirements thus making synchronization faster.
    • The app will work while offline, eventually syncing both the shared realm and the image realm when connection is restored.
    • The image Realm will not be synced to other devices, so there will not be any unnecessary traffic.

    And, as any solution goes, there are some drawbacks:

    • It will not work with the Developer edition as it requires modifying the objects on the server.
    • It may require some more advanced transaction error handling, as you want to commit two transactions in two different realms in a (preferably) atomic fashion.