cs-icon.svg

Using Realm Persistence Library With iOS 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 is 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 Contentstack Persistence Realm 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 following steps:

  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, perform the following steps to set up your ContentstackPersistenceRealm 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.

    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 and then 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 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 that we need to map in our Synchronization process are as follows:

  • Sync token/Pagination token
  • Entries
  • Assets

Let us look at how you can map these.

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 us consider an example of our “Conference” app. Let us say you have a content type named “Session.” To implement this example, we will perform the following.

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, 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

Following are some related articles that can help you understand other functionalities using iOS SDK:

Was this article helpful?
^