1

I am trying to share data between the main and widgets, I create UserDefault save data which I want then create an app group for both, and did try to read data from UserDefault but obtain nil.

I follow this info (https://betterprogramming.pub/sharing-object-data-between-an-ios-app-and-its-widget-a0a1af499c31) and many others but can't find a problem.

Before guide above, I am using the next code for save:

UserDefaults(suiteName: "group.url.scheme.firebase.widgets")!.set(try? PropertyListEncoder().encode(vpaid), forKey:"Widget")
        UserDefaults.standard.synchronize()

And for reading inside Widgets:

.onAppear {
            
            let sharedUsername = UserDefaults(suiteName: "group.url.scheme.firebase.widgets")!.string(forKey: "Widget")
            print("Shared username: \(String(describing: sharedUsername))")
 }

What I did wrong?

Ice
  • 680
  • 1
  • 10
  • 23
  • Some suggestions: try with simple integers/strings first, don't use `UserDefaults.standard.synchronize()`, make sure your app group is properly registered. Also this might help you: [Share data between main App and Widget in SwiftUI for iOS 14](https://stackoverflow.com/q/63922032/8697793) – pawello2222 Mar 02 '21 at 23:05
  • I have solved the problem using this answer https://stackoverflow.com/questions/50149072/transfer-data-from-project-to-widget-in-swift – Ice Mar 03 '21 at 08:26

0 Answers0