UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Easiest way to share data between app and widget?

Forums > SwiftUI

I'm dipping my toes into the cold stream of widgetkit and feel a bit lost.

What would be the easiest way to share data from the app (which displays a list of prices for precious metals, updated now and then) to a widget showing only one value? First I tought of @EnvironmentObject, but that won't work since the widget is a different target (right?). Any hints on how I should approach this?

3      

Sharing between main app and other targets is usually done with AppGroup which are capability you can turn on for your project. You then define app group name and this can be used to create special shared UserDefaults. So instead of standard one you use the initilizer UserDefaults(suiteName: ) where "suiteName" is the name of the app group.

This way you can easily share data.

3      

I understand the App Group + AppStorage w/ suiteName stuff but how can you get the Widget to trigger code that lives in the main app that will do user auth, fetch data and all the related logic I need before it ends up getting stored in the shared app group userdefaults?

I've read about breaking out some code into a shared framework that is imported into both the main app and the widget but I've been having issues with that as well.

3      

how can @AppStorage be used with a dictionary? i keep on getting No exact matches in call to initializer error

3      

This article gives a good walkthrough of sharing data with a widget:

https://medium.com/better-programming/sharing-object-data-between-an-ios-app-and-its-widget-a0a1af499c31

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.