Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
SwiftUI Essentials – iOS 14 Edition

You're reading from  SwiftUI Essentials – iOS 14 Edition

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801813228
Pages 494 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (56) Chapters

1. Start Here 2. Joining the Apple Developer Program 3. Installing Xcode 12 and the iOS 14 SDK 4. An Introduction to Xcode 12 Playgrounds 5. Swift Data Types, Constants and Variables 6. Swift Operators and Expressions 7. Swift Control Flow 8. The Swift Switch Statement 9. Swift Functions, Methods and Closures 10. The Basics of Swift Object-Oriented Programming 11. An Introduction to Swift Subclassing and Extensions 12. An Introduction to Swift Structures and Enumerations 13. An Introduction to Swift Property Wrappers 14. Working with Array and Dictionary Collections in Swift 15. Understanding Error Handling in Swift 5 16. An Overview of SwiftUI 17. Using Xcode in SwiftUI Mode 18. SwiftUI Architecture 19. The Anatomy of a Basic SwiftUI Project 20. Creating Custom Views with SwiftUI 21. SwiftUI Stacks and Frames 22. SwiftUI State Properties, Observable, State and Environment Objects 23. A SwiftUI Example Tutorial 24. SwiftUI Lifecycle Event Modifiers 25. SwiftUI Observable and Environment Objects – A Tutorial 26. SwiftUI Data Persistence using AppStorage and SceneStorage 27. SwiftUI Stack Alignment and Alignment Guides 28. SwiftUI Lists and Navigation 29. A SwiftUI List and Navigation Tutorial 30. An Overview of List, OutlineGroup and DisclosureGroup 31. A SwiftUI List, OutlineGroup and DisclosureGroup Tutorial 32. Building SwiftUI Grids with LazyVGrid and LazyHGrid 33. Building Tabbed and Paged Views in SwiftUI 34. Building Context Menus in SwiftUI 35. Basic SwiftUI Graphics Drawing 36. SwiftUI Animation and Transitions 37. Working with Gesture Recognizers in SwiftUI 38. Creating a Customized SwiftUI ProgressView 39. An Overview of SwiftUI DocumentGroup Scenes 40. A SwiftUI DocumentGroup Tutorial 41. An Introduction to SiriKit 42. A SwiftUI SiriKit Messaging Extension Tutorial 43. Customizing the SiriKit Intent User Interface 44. A SwiftUI SiriKit NSUserActivity Tutorial 45. An Overview of Siri Shortcut App Integration 46. A SwiftUI Siri Shortcut Tutorial 47. Building Widgets with SwiftUI and WidgetKit 48. A SwiftUI WidgetKit Tutorial 49. Supporting WidgetKit Size Families 50. A SwiftUI WidgetKit Deep Link Tutorial 51. Adding Configuration Options to a WidgetKit Widget 52. Integrating UIViews with SwiftUI 53. Integrating UIViewControllers with SwiftUI 54. Integrating SwiftUI with UIKit 55. Preparing and Submitting an iOS 14 Application to the App Store Index

26. SwiftUI Data Persistence using AppStorage and SceneStorage

It is a common requirement for an app to need to store small amounts of data which will persist through app restarts. This is particularly useful for storing user preference settings, or when restoring a scene to the exact state it was in last time it was accessed by the user. SwiftUI provides two property wrappers (@AppStorage and @SceneStorage) for the specific purpose of persistently storing small amounts of app data, details of which will be covered in this chapter.

26.1 The @SceneStorage Property Wrapper

The @SceneStorage property wrapper is used to store small amounts of data within the scope of individual app scene instances and is ideal for saving and restoring the state of a screen between app launches. Consider a situation where a user, partway through entering information into a form within an app, is interrupted by a phone call or text message, and places the app into the background. The user subsequently forgets to return to the app, complete the form and save the entered information. If the background app were to exit (either because of a device restart, the user terminating the app, or the system killing the app to free up resources) the partial information entered into the form would be lost. Situations such as this can be avoided, however, by using scene storage to retain and restore the data.

Scene storage is declared using the @SceneStorage property wrapper together with a key string value which is used internally to store the...

26.2 The @AppStorage Property Wrapper

The @SceneStorage property wrapper allows each individual scene within an app to have its own copy of stored data. In other words, the data stored by one scene is not accessible to any other scenes in the app (even other instances of the same scene). The @AppStorage property wrapper, on the other hand, is used to store data that is universally available throughout the entire app.

App Storage is built on top of UserDefaults, a feature which has been available in iOS for many years. Primarily provided as a way for apps to access and store default user preferences (such as language preferences or color choices), UserDefaults can also be used to store small amounts of data needed by the app in the form of key-value pairs.

As with scene storage, the @AppStorage property wrapper requires a string value to serve as a key and may be declared as follows:

@AppStorage("mystore") var mytext: String = ""

By default, data will...

26.3 Creating and Preparing the StorageDemo Project

Begin this tutorial by launching Xcode and selecting the options to create a new Multiplatform App project named StorageDemo.

Begin the project design by selecting the ContentView.swift file and changing the view body so that it contains a TabView as outlined below:

import SwiftUI

 

struct ContentView: View {

    

    var body: some View {

       

        TabView {

            SceneStorageView()

                .tabItem {

                    Image(systemName: "circle.fill")

          ...

26.4 Using Scene Storage

Edit the SceneStorageView.swift file and modify it so that it reads as follows:

import SwiftUI

 

struct SceneStorageView: View {

    

    @State private var editorText: String = ""

    

    var body: some View {

        TextEditor(text: $editorText)

            .padding(30)

            .font(.largeTitle)

    }

}

This declaration makes use of the TextEditor view. This is a view designed to allow multiline text to be displayed and edited within a SwiftUI app and includes scrolling when the displayed text extends beyond the viewable area. The TextEditor view is passed a binding to a state property into which any typed text will be stored (note that we...

26.5 Using App Storage

The final task in this tutorial is to demonstrate the use of app storage. Within Xcode, edit the AppStorageView.swift file and modify it so that it reads as follows:

import SwiftUI

 

struct AppStorageView: View {

 

    @AppStorage("mytext") var editorText: String = "Sample Text"

    

    var body: some View {

        TextEditor(text: $editorText)

            .padding(30)

            .font(.largeTitle)

    }

}

.

.

With the changes made, run the app on the iPad once again and repeat the steps to display two scene instances side-by-side. Select the App Storage tab within both scenes and note that the scene instances are displaying the default sample text...

26.6 Storing Custom Types

The @AppStorage and @SceneStorage property wrappers only allow values of certain types to be stored. Specifically Bool, Int, Double, String, URL and Data types. This means that any other type that needs to be stored must first be encoded as a Swift Data object in order to be stored and subsequently decoded when retrieved.

Consider, for example, the following struct declaration and initialization:

struct UserName {

    var firstName: String

    var secondName: String

}

 

var username = UserName(firstName: "Mark", secondName: "Wilson")

Because UserName is not a supported type, it is not possible to store our username instance directly into app or scene-based storage. Instead, the instance needs to be encoded and encapsulated into a Data instance before it can be saved. The exact steps to perform the encoding and decoding will depend on the type of the data being stored....

26.7 Summary

The @SceneStorage and @AppStorage property wrappers provide two ways to persistently store small amounts of data within a SwiftUI app. Scene storage is intended primarily for saving and restoring the state of a scene when an app is terminated while in the background. Each scene within an app has its own local scene storage which is not directly accessible to other areas of the app. App storage uses the UserDefaults system and is used for storing data that is to be accessible from anywhere within an app. Through the use of App Groups, app storage may also be shared between different targets within the same app project, or even entirely different apps. Changes to app storage are immediate regardless of whether the app is currently in the foreground or background.

Both the @AppStorage and @SceneStorage property wrappers support storing Bool, Int, Double, String, URL and Data types. Other types need to be encoded and encapsulated in Data objects before being placed into...

lock icon The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Essentials – iOS 14 Edition
Published in: May 2021 Publisher: Packt ISBN-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.
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}