Reader small image

You're reading from  SwiftUI Essentials – iOS 14 Edition

Product typeBook
Published inMay 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781801813228
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

25. SwiftUI Observable and Environment Objects – A Tutorial

The chapter entitled “SwiftUI State Properties, Observable, State and Environment Objects” introduced the concept of observable and environment objects and explained how these are used to implement a data driven approach to app development in SwiftUI.

This chapter will build on the knowledge from the earlier chapter by creating a simple example project that makes use of both observable and environment objects.

25.1 About the ObservableDemo Project

Observable objects are particularly powerful when used to wrap dynamic data (in other words, data values that change repeatedly). To simulate data of this type, an observable data object will be created which makes use of the Foundation framework Timer object configured to update a counter once every second. This counter will be published so that it can be observed by views within the app project.

Initially, the data will be treated as an observable object and passed from one view to another. Later in the chapter, the data will be converted to an environment object so that it can be accessed by multiple views without being passed between views.

25.2 Creating the Project

Launch Xcode and select the option to create a new Multiplatform App project named ObservableDemo.

25.3 Adding the Observable Object

The first step after creating the new project is to add a data class implementing the ObservableObject protocol. Within Xcode, select the File -> New -> File… menu option and, in the resulting template dialog, select the Swift File option. Click the Next button and name the file TimerData before clicking the Create button.

With the TimerData.swift file loaded into the code editor, implement the TimerData class as follows:

import Foundation

import Combine

 

class TimerData : ObservableObject {

    

    @Published var timeCount = 0

    var timer : Timer?

    

    init() {

        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerDidFire), userInfo: nil, repeats: true)

    }

    ...

25.4 Designing the ContentView Layout

The user interface for the app will consist of two screens, the first of which will be represented by the ContentView.Swift file. Select this file to load it into the code editor and modify it so that it reads as follows:

import SwiftUI

 

struct ContentView: View {

    

    @StateObject var timerData: TimerData = TimerData()

    

    var body: some View {

       

        NavigationView {

            VStack {

                Text("Timer count = \(timerData.timeCount)")

                

      &...

25.5 Adding the Second View

Select the File -> New -> File… menu option, this time choosing the SwiftUI View template option and naming the view SecondView. Edit the SecondView.swift file so that it reads as follows:

import SwiftUI

 

struct SecondView: View {

    

    @StateObject var timerData: TimerData

    

    var body: some View {

        

      VStack {

            Text("Second View")

                .font(.largeTitle)

            Text("Timer Count = \(timerData.timeCount)")

              &...

25.6 Adding Navigation

A navigation link now needs to be added to ContentView and configured to navigate to the second view. Open the ContentView.swift file in the code editor and add this link as follows:

var body: some View {

    

    NavigationView {

        VStack {

            Text("Timer count = \(timerData.timeCount)")

            

                .font(.largeTitle)

                .fontWeight(.bold)

                .padding()

            

&...

25.7 Using an Environment Object

The final step in this tutorial is to convert the observable object to an environment object. This will allow both views to access the same TimerData object without the need for a reference to be passed from one view to the other.

This change does not require any modifications to the TimerData.swift class declaration and only minor changes are needed within the two SwiftUI view files. Starting with the ContentView.swift file, modify the navigation link destination so that timerData is no longer passed through to SecondView. Also add a call to the environmentObject() modifier to insert the timerData instance into the view hierarchy environment:

import SwiftUI

 

struct ContentView: View {

    

@StateObject var timerData: TimerData = TimerData()

        

    var body: some View {

        

 ...

25.8 Summary

This chapter has worked through a tutorial that demonstrates the use of observed and environment objects to bind dynamic data to the views in a user interface, including implementing an observable object, publishing a property, subscribing to an observable object and the use of environment objects.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Essentials – iOS 14 Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801813228
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth