iOS Development

Interactive Widgets With SwiftUI | Kodeco

Spread the love


Apple launched Widgets in iOS 14 and introduced a recent look that modified our telephone’s dwelling screens. The framework advanced by the years, including a strong technique of conserving customers up to date with their knowledge.

iOS 17 takes widgets to the subsequent degree by introducing interactivity. Customers can now work together along with your app in a brand new, revolutionary means that wasn’t attainable earlier than.

By making your app’s important actions out there in a widget, your customers have a extra handy and interesting approach to work together along with your app.

On this tutorial, you’ll add interactive widgets to the Trask app utilizing SwiftUI.

For those who’re serious about studying SwiftUI, widgets’ easy views are an awesome place to begin with.

This tutorial covers the next matters.

  • What interactive widgets are and the way they work.
  • Find out how to create interactive widgets with a SwiftUI animation.
  • Various kinds of interactive widgets you could create.
  • Finest practices for designing and creating interactive widgets.

Though there aren’t any strict stipulations, a fundamental data of SwiftUI and WidgetKit could be useful. Anyway, don’t fear, you’ll have a fast recap to begin off on the proper foot.

Getting Began

Obtain the starter mission by clicking the Obtain Supplies button on the prime or backside of this tutorial. Open the starter mission (Trask.xcodeproj) within the Starter folder.
Construct and run the mission, and it’s best to see the Trask preliminary display screen.

Trask's main screen.

Trask is a basic tracker app that tracks totally different duties/issues/habits through the day, such because the variety of glasses of water, drugs, yoga, and so forth.
The primary time you launch the app, Trask creates some pattern knowledge so you may see the several types of duties you may create.

  • Process with a number of steps.
  • “TODO” job with only one step.

When tapping the plus button, the app advances the duty, and as soon as it reaches its goal, it passes within the carried out state.
The consumer can delete duties by swiping left on them and might add new ones utilizing the button on the backside of the View.

Recapping WidgetKit

Earlier than you get into the recent subject of this tutorial, familiarize your self with some fundamental ideas on WidgetKit to construct widespread terminology for the remainder of the tutorial.

Observe: To discover ways to add Widgets, and for a deep dive into Widgets, please check out the superb tutorial Getting Began With Widgets.

Including an iOS Widget

Trask comes with a static widget to observe the standing of a selectable job.
Add an occasion of the widget to see the way it appears to be like.

  1. Construct and run the mission.
  2. Decrease the app.
  3. Lengthy press on an empty space of the display screen.
  4. Then faucet the + button, seek for Trask, and choose the widget out there.

Add Trask Widget.

You’re now prepared to leap into the code construction to see the way it works.

Widget Code Construction

The TraskWidgets folder of the starter mission incorporates all of the information associated to the widget.

Making the Widget Interactive

Information Sharing With The App

Timeline Supplier

Updating Widgets

Kinds of Interactivity

Widgets and Intents

Including the Intent

As you might even see, the widget code is contained in a separate Xcode goal, and iOS runs the widget in a course of totally different from the app. This element might sound refined, however it’s essential when contemplating that the app and the widget must share the identical knowledge. The widget code can’t merely name some features within the app goal. Among the many totally different prospects, Trask makes use of a UserDefault retailer on an App Group container shared between the app and the widget.

Data Sharing.

Timeline is a key idea of Widgets. To protect battery and system sources, iOS doesn’t always run your widget. As an alternative, it asks your timeline supplier to generate a collection of timeline entries to render your widget and current it on the proper time.

Your TaskTimelineProvider defines three strategies.

As mentioned above, the timeline(for:in:) returns the array of entries on the specified time, however what occurs after the final widget view is offered? Enter the widget replace technique!

When returning the timeline of entries, you additionally present one technique for updating the timeline. You could select between the three choices under.

In our case, the Trask timeline supplier returns the .by no means insurance policies since there isn’t any want for the widget to replace its view. The one approach to replace the standing of a job is thru the app when the consumer faucets to step a job…till the subsequent chapter. :]

Wow…that was an extended warmup, however now you’re prepared so as to add interplay to the Trask standing widget.

Beginning with iOS 17, iPadOS 17 and macOS 14, Apple permits two major methods of interactivity along with your widget: buttons and toggles.

As the primary enchancment, you’ll add a step button to the Trask Standing Widget so customers can progress their favourite duties with out opening the app.

When including interactivity, the widget’s button can’t invoke code in your app, however it does must depend on a public API uncovered by your app: App Intents.

App intents expose actions of your app to the system in order that iOS can carry out them when wanted. For instance, when the consumer interacts with the widget button.

Widgets and Intent.

Moreover, you too can use the identical App Intent for Siri and Shortcuts.

Firstly, add the intent technique that your button will invoke when pressed. Open TaskIntent.swift and add the carry out() technique to TaskIntent.

The AppIntent‘s carry out() technique is the one known as when an Intent is invoked. This technique takes the chosen job as enter and calls a way within the retailer to progress this job.

Please be aware that UserDefaultStore is a part of each the app and the widget extension so as to reuse the identical code in each targets. :]

Subsequent, open TaskStore.swift and add a definition of the stepTask(_:) technique to the protocol TaskStore.

Then, add the stepTask(_:) technique to UserDefaultStore. This technique hundreds all of the duties contained within the retailer, finds the required job, calls the duty’s progress() technique and saves it again within the retailer.

Lastly, add an empty stepTask(_:) technique to SampleStore to make it compliant with the brand new protocol definition.

    • TaskIntent is an intent conforming to the WidgetConfigurationIntent protocol. Right here, the intent permits the duty choice within the Edit Widget menu.
    • TaskStatusWidget is the precise widget. 4 components compose the widget file.

      • TaskTimelineProvider specifies when iOS ought to refresh the widget display screen.
      • TaskEntry represents the mannequin of the widget view. It incorporates a date iOS makes use of to replace the widget view with the duty merchandise.
      • TaskStatusWidgetEntryView defines the widget view utilizing SwiftUI. It incorporates a timeline entry as a parameter, and it ought to lay out the widget primarily based on this parameter worth.
      • TaskStatusWidget binds all of the components collectively inside a WidgetConfiguration.
      • Lastly, TraskWidgetBundle declares all of the extension’s widgets.
      • placeholder(in:) ought to return some pattern knowledge to render the placeholder UI whereas ready for the widget to be prepared. SwiftUI applies a redaction impact to this view.
      • snapshot(for:in:) offers the info to render the widget within the gallery offered when selecting a widget.
      • timeline(for:in:) is the principle technique that returns the timeline entries to current on the specified time.
      • .atEnd recomputes the timeline after the final date within the timeline passes.
      • .after(_:) specifies roughly when to request a brand new timeline.
      • .by no means tells the system to by no means recompute the timeline. The app will immediate WidgetKit when a brand new timeline is accessible.
      • Buttons are appropriate to signify an motion on the widget content material.
      • Toggles higher establish a binary actionable state on/off. Comparable to our TODO job standing.

      Observe: On a locked machine, buttons and toggles are inactive, and iOS doesn’t carry out actions till the consumer unlocks his machine.

      func carry out() async throws -> some IntentResult {
        UserDefaultStore().stepTask(taskEntity.job)
        return .outcome()
      }
      
      protocol TaskStore {
        func loadTasks() -> [TaskItem]
        func saveTasks(_ duties: [TaskItem])
        func stepTask(_ job: TaskItem)
      }
      
      func stepTask(_ job: TaskItem) {
        var duties = loadTasks()
        guard let index = duties.firstIndex(the place: { $0.id == job.id }) else { return }
      
        duties[index].progress()
        saveTasks(duties)
      }
      
  • TaskIntent is an intent conforming to the WidgetConfigurationIntent protocol. Right here, the intent permits the duty choice within the Edit Widget menu.
  • TaskStatusWidget is the precise widget. 4 components compose the widget file.

    • TaskTimelineProvider specifies when iOS ought to refresh the widget display screen.
    • TaskEntry represents the mannequin of the widget view. It incorporates a date iOS makes use of to replace the widget view with the duty merchandise.
    • TaskStatusWidgetEntryView defines the widget view utilizing SwiftUI. It incorporates a timeline entry as a parameter, and it ought to lay out the widget primarily based on this parameter worth.
    • TaskStatusWidget binds all of the components collectively inside a WidgetConfiguration.
    • Lastly, TraskWidgetBundle declares all of the extension’s widgets.
    • placeholder(in:) ought to return some pattern knowledge to render the placeholder UI whereas ready for the widget to be prepared. SwiftUI applies a redaction impact to this view.
    • snapshot(for:in:) offers the info to render the widget within the gallery offered when selecting a widget.
    • timeline(for:in:) is the principle technique that returns the timeline entries to current on the specified time.
    • .atEnd recomputes the timeline after the final date within the timeline passes.
    • .after(_:) specifies roughly when to request a brand new timeline.
    • .by no means tells the system to by no means recompute the timeline. The app will immediate WidgetKit when a brand new timeline is accessible.
    • Buttons are appropriate to signify an motion on the widget content material.
    • Toggles higher establish a binary actionable state on/off. Comparable to our TODO job standing.

    Observe: On a locked machine, buttons and toggles are inactive, and iOS doesn’t carry out actions till the consumer unlocks his machine.

    func carry out() async throws -> some IntentResult {
      UserDefaultStore().stepTask(taskEntity.job)
      return .outcome()
    }
    
    protocol TaskStore {
      func loadTasks() -> [TaskItem]
      func saveTasks(_ duties: [TaskItem])
      func stepTask(_ job: TaskItem)
    }
    
    func stepTask(_ job: TaskItem) {
      var duties = loadTasks()
      guard let index = duties.firstIndex(the place: { $0.id == job.id }) else { return }
    
      duties[index].progress()
      saveTasks(duties)
    }
    
  • TaskTimelineProvider specifies when iOS ought to refresh the widget display screen.
  • TaskEntry represents the mannequin of the widget view. It incorporates a date iOS makes use of to replace the widget view with the duty merchandise.
  • TaskStatusWidgetEntryView defines the widget view utilizing SwiftUI. It incorporates a timeline entry as a parameter, and it ought to lay out the widget primarily based on this parameter worth.
  • TaskStatusWidget binds all of the components collectively inside a WidgetConfiguration.
  • Lastly, TraskWidgetBundle declares all of the extension’s widgets.
  • placeholder(in:) ought to return some pattern knowledge to render the placeholder UI whereas ready for the widget to be prepared. SwiftUI applies a redaction impact to this view.
  • snapshot(for:in:) offers the info to render the widget within the gallery offered when selecting a widget.
  • timeline(for:in:) is the principle technique that returns the timeline entries to current on the specified time.
  • .atEnd recomputes the timeline after the final date within the timeline passes.
  • .after(_:) specifies roughly when to request a brand new timeline.
  • .by no means tells the system to by no means recompute the timeline. The app will immediate WidgetKit when a brand new timeline is accessible.
  • Buttons are appropriate to signify an motion on the widget content material.
  • Toggles higher establish a binary actionable state on/off. Comparable to our TODO job standing.

Observe: On a locked machine, buttons and toggles are inactive, and iOS doesn’t carry out actions till the consumer unlocks his machine.

func carry out() async throws -> some IntentResult {
  UserDefaultStore().stepTask(taskEntity.job)
  return .outcome()
}
protocol TaskStore {
  func loadTasks() -> [TaskItem]
  func saveTasks(_ duties: [TaskItem])
  func stepTask(_ job: TaskItem)
}
func stepTask(_ job: TaskItem) {
  var duties = loadTasks()
  guard let index = duties.firstIndex(the place: { $0.id == job.id }) else { return }

  duties[index].progress()
  saveTasks(duties)
}
func stepTask(_ job: TaskItem) {}

Leave a Reply

Your email address will not be published. Required fields are marked *