Using Realm Persistence Library with iOS Sync SDK

Contentstack’s Realm Persistence Library for iOS SDK helps you save the app data on the device that it is being accessed on. This enables your app to serve data offline, i.e., even when it’s not connected to the internet.

This Persistent Library contains methods that are required to map data fields of your content types and Realm for data storage.

Let’s look at how to use this library for your Contentstack-powered iOS apps.

Note: If you have just started with iOS SDK and Contenstack, we recommend reading more about Realm and Contentstack docs before proceeding with the following steps.

Prerequisites

Installation and usage

To sync data from Contentstack to Realm we need to download and install Realm and ContentstackPersistenceRealm iOS Library. Let's go through the installation processes in detail.

Install and set up Realm

We need to first download Realm and install it. To do so, perform the steps given below:

  1. Download the latest version of Realm for Objective C.
  2. In your Podfile, add pods named Realm and Realm/Headers to your ‘app’ and ‘test’ targets, respectively.
  3. From the command line, run pod install.
  4. Use the .xcworkspace file generated by CocoaPods to work on your project.

Install ContentstackPersistenceRealm iOS Library

Now that your Realm framework is ready, let's look at the steps involved in setting up your Contentstack iOS SDK.

You can configure the SDK in two ways – installation using CocoaPods and manual installation.

Method 1: Using Cocoapods

  1. Add the following command to your Podfile:
    pod 'ContentstackPersistenceRealm'
  2. Then, run the command given below to get the latest release of Contentstack.
    pod install

Method 2: Manual method

  1. Download and set up the Contentstack iOS Persistence Library from here.

    You will find the ContentstackPersistence folder, which contains the following four files:
    • SyncManager.h
    • SyncManager.m
    • SyncPersistable.h
    • SyncProtocol.h

    Next, you will find the ContentstackPersistenceRealm folder, which contains the following two files:
    • RealmStore.h
    • RealmStore.m
  2. Add the ContentstackPersistence and ContentstackPersistenceRealm folder to your project.
  3. Add the Bridge.h header file. Import the SyncManager.h file using the command given below:
    #import "SyncManager.h"

Map data

To start mapping of data, first, you need to create a content type schema (in Contentstack) as per your app design and create entries. For your convenience, we have already created the necessary content types. Download them from here and import them to your app’s stack in Contentstack.

Next, create entries for the imported content types. In order to sync this data with Realm, we need to add data mappings. The three important items to be mapped in our Synchronization process are as follows:

  • Sync token/Pagination token
  • Entries
  • Assets

Let’s look at how each of the above can be mapped.

Sync token mapping

To save sync token and pagination token, you need to create a new file (File > New > File) named SyncStore extending RLMObject, and add the following code to implement SyncStoreProtocol:

class SyncStore: RLMObject, SyncStoreProtocol {
    @objc dynamic var syncToken: String!
    @objc dynamic var paginationToken: String!
}

Entry mapping

To begin with, let’s consider an example of our Conference app. Let’s say you have a content type named Session. Let’s see how to implement this example.

Create a new file (File > New > File) named Session extending RLMObject, and add following code to implement EntityProtocol as shown below:

class Session: RLMObject, EntryProtocol {
    @objc dynamic var sessionId = 0
    @objc dynamic var type: String!
    @objc dynamic var title: String!
    @objc dynamic var desc: String!
    @objc dynamic var url: String!
    @objc dynamic var uid: String!
    @objc dynamic var publishLocale: String!
    @objc dynamic var createdAt: Date!
    @objc dynamic var updatedAt: Date!
    @objc dynamic var locale: String!
    @objc dynamic var isPopular = false
    @objc dynamic var startTime: Date!
    @objc dynamic var endTime: Date!
    static func contentTypeid() -> String! {
        return "session"
    }
    static func fieldMapping() -> [AnyHashable : Any]! {
        return ["sessionId":"session_id",
                "desc": "description",
                "type":"type",
                "isPopular":"is_popular",
                "startTime":"start_time",
                "endTime":"end_time"]
    }    
}

In the above code, we have to implement contentTypeid for which you are mapping the Entry content type.

You also need to implement the fieldMapping function, which returns the mapping of the attributes and entry fields in Contentstack.

Similarly, we can add other entities and perform mapping for each entity.

Asset mapping

To save assets, you need to create a new file (File > New > File) named Assets extending RLMObject, and add the following code to implement AssetProtocol.

class Assets: RLMObject, AssetProtocol{
    @objc dynamic var publishLocale: String!
    @objc dynamic var title: String!
    @objc dynamic var uid: String!
    @objc dynamic var createdAt: Date!
    @objc dynamic var updatedAt: Date!
    @objc dynamic var fileName: String!
    @objc dynamic var url: String!
}

Now, the final step is to initiate SyncManager and begin with the sync process.

Initiate SyncManager and Sync

After content mapping, initiate SyncManager by providing the required details:

static var stack : Stack = Contentstack.stack(withAPIKey: StackConfig.APIKey, accessToken: StackConfig.AccessToken, environmentName: StackConfig.EnvironmentName, config:StackConfig._config)
var realmStore = RealmStore(realm: try? RLMRealm(configuration: RLMRealmConfiguration.default()))
var syncManager : SyncManager = SyncManager(stack: stack, persistance: realmStore)
self.syncManager.sync { (totalCount, loadedCount, error) in
}

Helpful links

Was this article helpful?
top-arrow