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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.