Design+Code logo

Quick links

Suggested search

Installation

Install Realm through Swift Package Manager. Learn how to install it with SPM in the Swift Package Manager section of the SwiftUI Handbook. In the search box, paste the following link to Realm's Github repository in order to fetch the package.

https://github.com/realm/realm-cocoa.git

When asked for the packages you want to install into your project, check the two of them.

Install Realm

Create a RealmManager class

Once the package is installed, create a class called RealmManager, where you will manage everything related to Realm. It'll conform to an ObservableObject. Don't forget to import RealmSwift at the top.

// RealmManager.swift

import Foundation
import RealmSwift

class RealmManager: ObservableObject {

}

Open a Realm

Create a variable, called localRealm, in which you'll save your Realm.

// RealmManager.swift

private(set) var localRealm: Realm?

To open a Realm, use the following code. Before creating our local Realm, we are setting its configuration. Remember to increment the schemaVersion any time you update your Realm schema. Then, we're opening a Realm and it will be saved into the localRealm variable we just created.

// RealmManager.swift

func openRealm() {
    do {
        let config = Realm.Configuration(schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in
            if oldSchemaVersion > 1 {
                // Do something, usually updating the schema's variables here
            }
        })

        Realm.Configuration.defaultConfiguration = config

        localRealm = try Realm()
    } catch {
        print("Error opening Realm", error)
    }
}

Call the openRealm function on initialize of your RealmManager class.

// RealmManager.swift

init() {
    openRealm()
}

Create your Realm object

In order to save data in a Realm, we need to create a Realm object (a Realm model). Note that this Realm object should be at the top-level of your app, so it should be outside of the RealmManager class.

Let's create a new file called Course.swift and save our Course object there. Each Course object will contain a title, an optional subtitle and a numberOfSections.

// Course.swift

import Foundation
import RealmSwift

class Course: Object {
		@objc dynamic var id = 1
    @objc dynamic var title = ""
    @objc dynamic var subtitle: String?
    @objc dynamic var numberOfSections = 10
}

Write to Realm

To create a new course and add it to your Realm, use the function below. We are creating a course within the function and will try to write it into the localRealm we opened.

// RealmManager.swift

func addCourse() {
    if let localRealm = localRealm {
        do {
            try localRealm.write {
                let newCourse = Course()
                newCourse.id = Int.random(in: 0...100)
                newCourse.title = "Advanced Development in SwiftUI"
                newCourse.subtitle = "Advance your SwiftUI skills by developing an app using Core Data, CloudKit, In App Purchases, Sign In With Apple, and Firebase Authentication"
                newCourse.numberOfSections = 20

                localRealm.add(newCourse)
                print("Added new course to Realm!")
            }
        } catch {
            print("Error adding course to Realm", error)
        }
    }
}

And let's call the addCourse function on initialize of the RealmManager.

// RealmManager.swift

init() {
    openRealm()
		addCourse()
}

Read from Realm

Create a local variable where we'll save the courses.

// RealmManager.swift

@Published var courses: [Course] = []

Create the getCourses function to get all the courses saved in Realm.

// RealmManager.swift

func getCourses() {
    if let localRealm = localRealm {
        let allCourses = localRealm.objects(Course.self)
        allCourses.forEach { course in
            courses.append(course)
        }
    }
}

We can call this function on initialize of the RealmManager class.

// RealmManager.swift

init() {
    openRealm()
		addCourse()
		getCourses()
}

Delete from Realm

// RealmManager.swift

func deleteCourse(id: Int) {
    if let localRealm = localRealm {
        let allCourses = localRealm.objects(Course.self)
        let course = allCourses.filter("id == \(id)")
        guard !course.isEmpty else { return }

        do {
            try localRealm.write {
                localRealm.delete(course)
                courses = []
                getCourses()
                print("Course deleted from Realm")
            }
        } catch {
            print("Error deleting course", error)
        }

    }
}

Connect to View

Now that we have all the functions in our RealmManager, let's initialize our it in our ContentView, at the top of our file.

// ContentView.swift

@StateObject var realmManager = RealmManager()

Let's iterate through the courses and, for each course, display a row with the course title and a trash can image so that we can delete the course.

// ContentView.swift

VStack(spacing: 10) {
    ForEach(realmManager.courses, id: \.id) { course in
        HStack {
            Text(course.title)
            Spacer()
            Image(systemName: "trash")
        }
        .padding(.horizontal, 20)
    }
}

On the image, we'll add an onTapGesture and call the deleteCourse function from our RealmManager.

// ContentView.swift

Image(systemName: "trash")
    .onTapGesture {
        realmManager.deleteCourse(id: course.id)
    }

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Download Files Locally Part 2

READ NEXT

HTTP Request with Async Await

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Videos

Assets

ePub

Subtitles

1

Firebase Auth

How to install Firebase authentification to your Xcode project

8:18

2

Read from Firestore

Install Cloud Firestore in your application to fetch and read data from a collection

8:01

3

Write to Firestore

Save the data users input in your application in a Firestore collection

5:35

4

Join an Array of Strings

Turn your array into a serialized String

3:33

5

Data from JSON

Load data from a JSON file into your SwiftUI application

5:08

6

HTTP Request

Create an HTTP Get Request to fetch data from an API

6:31

7

WKWebView

Integrate an HTML page into your SwiftUI application using WKWebView and by converting Markdown into HTML

5:25

8

Code Highlighting in a WebView

Use Highlight.js to convert your code blocks into beautiful highlighted code in a WebView

5:11

9

Test for Production in the Simulator

Build your app on Release scheme to test for production

1:43

10

Debug Performance in a WebView

Enable Safari's WebInspector to debug the performance of a WebView in your application

1:57

11

Debug a Crash Log

Learn how to debug a crash log from App Store Connect in Xcode

2:22

12

Simulate a Bad Network

Test your SwiftUI application by simulating a bad network connection with Network Link Conditionner

2:11

13

Archive a Build in Xcode

Archive a build for beta testing or to release in the App Store

1:28

14

Apollo GraphQL Part I

Install Apollo GraphQL in your project to fetch data from an API

6:21

15

Apollo GraphQL Part 2

Make a network call to fetch your data and process it into your own data type

6:43

16

Apollo GraphQL Part 3

Display the data fetched with Apollo GraphQL in your View

5:08

17

Configuration Files in Xcode

Create configuration files and add variables depending on the environment - development or production

4:35

18

App Review

Request an app review from your user for the AppStore

5:43

19

ImagePicker

Create an ImagePicker to choose a photo from the library or take a photo from the camera

5:06

20

Compress a UIImage

Compress a UIImage by converting it to JPEG, reducing its size and quality

3:32

21

Firebase Storage

Upload, delete and list files in Firebase Storage

11:11

22

Search Feature

Implement a search feature to filter through your content in your SwiftUI application

9:13

23

Push Notifications Part 1

Set up Firebase Cloud Messaging as a provider server to send push notifications to your users

5:59

24

Push Notifications Part 2

Create an AppDelegate to ask permission to send push notifications using Apple Push Notifications service and Firebase Cloud Messaging

6:30

25

Push Notifications Part 3

Tie everything together and test your push notifications feature in production

6:13

26

Network Connection

Verify the network connection of your user to perform tasks depending on their network's reachability

6:49

27

Download Files Locally Part 1

Download videos and files locally so users can watch them offline

6:05

28

Download Files Locally Part 2

Learn how to use the DownloadManager class in your views for offline video viewing

6:02

29

Offline Data with Realm

Save your SwiftUI data into a Realm so users can access them offline

10:20

30

HTTP Request with Async Await

Create an HTTP get request function using async await

6:11

31

Xcode Cloud

Automate workflows with Xcode Cloud

9:23

32

SceneStorage and TabView

Use @SceneStorage with TabView for better user experience on iPad

3:52

33

Network Connection Observer

Observe the network connection state using NWPathMonitor

4:37

34

Apollo GraphQL Caching

Cache data for offline availability with Apollo GraphQL

9:42

35

Create a model from an API response

Learn how to create a SwiftUI model out of the response body of an API

5:37

36

Multiple type variables in Swift

Make your models conform to the same protocol to create multiple type variables

4:23

37

Parsing Data with SwiftyJSON

Make API calls and easily parse data with this JSON package

9:36

38

ShazamKit

Build a simple Shazam clone and perform music recognition

12:38

39

Firebase Remote Config

Deliver changes to your app on the fly remotely

9:05