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

48. A SwiftUI WidgetKit Tutorial

From the previous chapter we now understand the elements that make up a widget and the steps involved in creating one. In this, the first of a series of tutorial chapters dedicated to WidgetKit, we will begin the process of creating an app which includes a widget extension. On completion of these tutorials, a functioning widget will have been created, including widget design and the use of timelines, support for different size families, deep links, configuration using intents and basic intelligence using SiriKit donations and relevance.

48.1 About the WidgetDemo Project

The project created in this tutorial can be thought of as the early prototype of a weather app designed to teach children about weather storms. The objective is to provide the user with a list of severe weather systems (tropical storms, thunderstorms etc.) and, when a storm type is selected, display a second screen providing a description of the weather system.

A second part of the app is intended to provide real-time updates on severe weather occurring in different locations around the world. When a storm is reported, a widget will be updated with information about the type and location of the storm, together with the prevailing temperature. When the widget is tapped by the user, the app will open the screen containing information about that storm category.

Since this app is an early prototype, however, it will only provide weather updates from two cities, and that data will be simulated rather than obtained from a real weather service. The...

48.2 Creating the WidgetDemo Project

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

48.3 Building the App

Before adding the widget extension to the project, the first step is to build the basic structure of the app. This will consist of a List view populated with some storm categories which, when selected, will appear in a detail screen.

The detail screen will be declared in a new SwiftUI View file named WeatherDetailView.swift. Within the project navigator panel, right-click on the Shared folder and select the New File… menu option. In the resulting dialog, select the SwiftUI View template option and click on the Next button. Name the file WeatherDetailView.swift before creating the file.

With the WeatherDetailView.swift file selected, modify the view declaration so that it reads as follows:

import SwiftUI

 

struct WeatherDetailView: View {

    

    var name: String

    var icon: String

    

    var body: some View {

&...

48.4 Adding the Widget Extension

The next step in the project is to add the widget extension by selecting the File -> New -> Target… menu option. From within the target template panel, select the Widget Extension option as shown in Figure 48-3 before clicking on the Next button:

Figure 48-3

On the subsequent screen, enter WeatherWidget into the product name field. When the widget is completed, the user will be able to select the geographical location for which weather updates are to be displayed. To make this possible the widget will need to use the intent configuration type. Before clicking on the Finish button, therefore, make sure that the Include Configuration Intent option is selected as shown in Figure 48-4:

Figure 48-4

When prompted, click on the Activate button to activate the extension within the project scheme. This will ensure that the widget is included in the project build process:

Figure 48-5

Once the extension has been added...

48.5 Adding the Widget Data

Now that the widget extension has been added to the project, the next step is to add some data and data structures that will provide the basis for the widget timeline. Begin by right-clicking on the Shared folder in the project navigator and selecting the New File… menu option.

From the template selection panel, select the Swift File entry, click on the Next button and name the file WeatherData.swift. Before clicking on the Create button, make sure that the WeatherWidgetExtension entry is enabled in the Targets section of the panel as shown in Figure 48-7 so that the file will be accessible to the extension:

Figure 48-7

As outlined in the previous chapter, each point in the widget timeline is represented by a widget timeline entry instance. Instances of this structure contain the date and time that the entry is to be presented by the widget, together with the data to be displayed. Within the WeatherData.swift file, add a TimelineEntry...

48.6 Creating Sample Timelines

Since this prototype app does not have access to live weather data, the timelines used to drive the widget content will contain sample weather entries for two cities. Remaining within the WeatherData.swift file, add these timeline declarations as follows:

.

.

let londonTimeline = [

    WeatherEntry(date: Date(), city: "London", temperature: 87,

          description: "Hail Storm", icon: "cloud.hail",

                image: "hail"),

    WeatherEntry(date: Date(), city: "London", temperature: 92,

          description: "Thunder Storm", icon: "cloud.bolt.rain",

             ...

48.7 Adding Image and Color Assets

Before moving to the next step of the tutorial, some image and color assets need to be added to the asset catalog of the widget extension.

Begin by selecting the Assets.xcassets file located in the WeatherWidget folder in the project navigator panel as highlighted in Figure 48-8:

Figure 48-8

Add a new entry to the catalog by clicking on the button indicated by the arrow in Figure 48-8 above. In the resulting menu, select the Color Set option. Click on the new Color entry and change the name to weatherBackgroundColor. With this new entry selected, click on the Any Appearance block in the main panel as shown in Figure 48-9:

Figure 48-9

Referring to the Color section of the attributes inspector panel, set Content to Display P3, Input Method to 8-bit Hexadecimal and the Hex field to #4C5057:

Figure 48-10

Select the Dark Appearance and make the same attribute changes, this time setting the Hex value to #3A4150.

Next...

48.8 Designing the Widget View

Now that the widget entry has been created and used as the basis for some sample timeline data, the widget view needs to be designed. When the widget extension was added to the project, a template widget entry view was included in the WeatherWidget.swift file which reads as follows:

struct WeatherWidgetEntryView : View {

    var entry: Provider.Entry

 

    var body: some View {

        Text(entry.date, style: .time)

    }

}

As currently implemented, the view is passed a widget entry from which the date value is extracted and displayed on a Text view.

Modify the view structure so that it reads as follows, keeping in mind that it will result in syntax errors appearing in the editor. These will be resolved later in the tutorial:

struct WeatherWidgetView: View {

    var entry: Provider.Entry

 ...

48.9 Modifying the Widget Provider

When the widget extension was added to the project, Xcode added a widget provider to the WeatherWidget.swift file. This declaration now needs to be modified to make use of the WeatherEntry structure declared in the WeatherData.swift file. The first step is to modify the getSnapshot() method to use WeatherEntry and to return an instance populated with sample data:

.

.

struct Provider: IntentTimelineProvider {

    func getSnapshot(for configuration: ConfigurationIntent, with context: Context, completion: @escaping (WeatherEntry) -> ()) {

       

        let entry = WeatherEntry(date: Date(), city: "London",

                    temperature: 89, description: "Thunder Storm",

      ...

48.10 Configuring the Placeholder View

The Final task before previewing the widget is to make sure that the placeholder view has been implemented. Xcode will have already created a placeholder() method for this purpose within the WeatherWidget.swift file which reads as follows:

func placeholder(in context: Context) -> SimpleEntry {

   SimpleEntry(date: Date(), configuration: ConfigurationIntent())

}

This method now needs to be modified so that it returns a WeatherWidget instance populated with some sample data as follows:

func placeholder(in context: Context) -> WeatherEntry {

    WeatherEntry(date: Date(), city: "London",

                       temperature: 89, description: "Thunder Storm",

               ...

48.11 Previewing the Widget

Using the preview canvas, verify that the widget appears as shown in Figure 48-12 below:

Figure 48-12

Next, test the widget on a device or simulator by changing the active scheme in the Xcode toolbar to the WeatherWidgetExtension scheme before clicking on the run button:

Figure 48-13

After a short delay, the widget will appear on the home screen and cycle through the different weather events at 30 second intervals:

Figure 48-14

48.12 Summary

The example project created in this chapter has demonstrated how to use WidgetKit to create a widget extension for an iOS app. This included the addition of the extension to the project, the design of the widget view and entry together with the implementation of a sample timeline. The widget created in this chapter, however, has not been designed to make use of the different widget size families supported by WidgetKit, a topic which will be covered in the next chapter.

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}