Realm database: Replacing SQLite & Core Data Part 2 to 2

Gerardo Lopez Falcón
ninjadevs
Published in
5 min readSep 8, 2017

In the previous tutorial, I was explaining to how setup a project in Swift using Realm Database instead of Core Data. The goal of this post is create all the stuff necessary for persisting data on the device. Get started.

Use a Realm List to display Tasks in the table view

Add the following property to your ViewController class, on a new line, right after the class declaration:

var items = List<Task>()

Add the following line to the end of your viewDidLoad() function to seed the list with some initial data:

override func viewDidLoad() {
// ... existing function ...
items.append(Task(value: ["text": "My First Task"]))
}

Append the following to the end of your ViewController class’s body:

// MARK: UITableViewoverride func tableView(_ tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let item = items[indexPath.row]
cell.textLabel?.text = item.text
cell.textLabel?.alpha = item.completed ? 0.5 : 1
return cell
}

If you then build and run the app, you’ll see your one task being displayed in the table. There’s also some code in here to show completed items as a little lighter than uncompleted items, but we won’t see that in action until later.

Add support for creating new tasks

Delete the line in your viewDidLoad() function that seeded initial data:

override func viewDidLoad() {
// -- DELETE THE FOLLOWING LINE --
items.append(Task(value: ["text": "My First Task"]))
}

Add the following function to your ViewController class at its end:

// MARK: Functionsfunc add() {
let alertController = UIAlertController(title: "New Task", message: "Enter Task Name", preferredStyle: .alert)
var alertTextField: UITextField!
alertController.addTextField { textField in
alertTextField = textField
textField.placeholder = "Task Name"
}
alertController.addAction(UIAlertAction(title: "Add", style: .default) { _ in
guard let text = alertTextField.text , !text.isEmpty else { return }
self.items.append(Task(value: ["text": text]))
self.tableView.reloadData()
})
present(alertController, animated: true, completion: nil)
}

Now add the following line at the end of the setupUI() function:

func setupUI() {
// ... existing function ...
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add))
}

Back items by a Realm and integrate sync

Now, add the following properties to your ViewController class, just under the items property:

var notificationToken: NotificationToken!
var realm: Realm!

The notification token we just added will be needed when we start observing changes from the Realm.

Right after the end of the setupUI() function, add the following:

func setupRealm() {
// Log in existing user with username and password
let username = "test" // <--- Update this
let password = "test" // <--- Update this
}
deinit {
notificationToken.stop()
}

In the code above, enter the same values for the username and password variables as you used when registering a user through the Realm Object Server. If you forgot it, please jump to install the MacOS bundle.

Then insert the following at the end of the setupRealm() function (inside the function body):

And, call this setup function at the end of the viewDidLoad() function:

override func viewDidLoad() {
// ... existing function ...
setupRealm()
}

Now edit the add() function to look like this:

This deletes two lines in the guard block that begin with self. and replaces them with a let and try!block which will actually write a new task to the Realm.

Lastly, we need to allow non-TLS network requests to talk to our local sync server.

Right-click on the Info.plist file and select “Open as… Source Code” and paste the following in the <dict>section:

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

If you build and run the app now, it should connect to the object server and display the tasks that were added in RealmTasks earlier.

If you add new tasks by tapping the “Add” button in your app, you should immediately see them reflected in your Realm Object server too.

Congratulations, you’ve built your first synced Realm app!

Keep going if you’d like to see how easy it is to add more functionality and finish building your task management app.

Support moving and deleting tasks

Add the following line to the end of your setupUI() function:

navigationItem.leftBarButtonItem = editButtonItem

Now, add these functions to the ViewController class body, right after the other tableView functions:

If you press the Edit Button, each task’ll has the option of deleting itself.

Support toggling the ‘completed’ state of a task by tapping it

After the last tableView function in the ViewController class, add the following function override:

If you press over any task, the task color will change, it indicate that the task has the completed status. If you want to reverse it, you only need to press it again and the task will come back to uncompleted status.

You’re a genius!!!

Now you’ve completed writing a minimal task management app that syncs its data in real time!

Thank you for reading, until the next time!

--

--

Gerardo Lopez Falcón
ninjadevs

Google Developer Expert & Sr Software Engineer & DevOps &. Soccer Fan