How to share Realm DB with Widget Target on existing project— iOS & Swift

Enes Buğra Yenidünya
2 min readSep 20, 2021

--

Past week I was trying to add new widgets for my app Candlewaster but there was one barrier for me to implement them easily. I’m using Realm DB for storing app data and for sharing that data with the Widgets, you must share the DB on App Groups so you can read the data from another app targets. It may be look easy task but I couldn't find any example for the Realm DB and I decided to create one 🤓

Note: This article shows to steps if you have that implemented Realm DB already and want to implement Widgets. Of course you can use only necessary parts for implementing from scratch with both.

Old App Delegate

Let’s say you already instantiated the Realm DB with realm config. The code would looks like below:

Think about this code is on live and you have to share your Realm DB with another target. The new App Target is “Widget Extension” in our scenario.

You should be careful because if you make mistake your users will lose their data. For sharing any kind of data you have to add “App Groups” to your required targets. With “App Group Identifier” you can specify a shared path to your Realm DB and read the new path from all targets. Thats what we need!

Creating App Group Identifier

App Groups

As you can see above screen shot after following below steps you will add new App Group Identifiers. Don’t forget to add same identifiers to both App Targets.

Signing & Capabilities -> + Capability -> App Groups

After adding them now we are ready to configure the App Delegate.

New App Delegate

Above code represents to successfull Realm DB sharing with other App Targets. Read the comments inside code and after understanding the precess we can now read the Realm DB from our newly created App Target ( Widget Extension).

Let’s assume that you have “Book” object and you want to get all your Books from Realm DB. Look at the code below and see how you can read your data from shared Realm DB.

I hope this article will help you to getting data from Realm Db and using it for the Widget Extension. Please comment out what you thinking and let me know if you have better idea! Lastly, don't hesitate to ask questions.

Follow me on Twitter, GitHub and Linkedin.

--

--

Enes Buğra Yenidünya
Enes Buğra Yenidünya

Written by Enes Buğra Yenidünya

iOS Engineer — Freelancer #iOS #swift #mobileappdevelopment #software #apple

Responses (1)