4

I want to share one variable from my UIKit File to my Widget Extension created with SwiftUI. I followed this here. Please look at the answer from J Arango.

But i dont understand the last part there. I have to use import MySharedObjects.

So I did this:

    import MySharedObject

struct testing {
    let mySharedObject = MySharedObject(name: "My Name", lastName: "My Last Name")
                       
     do {
         let data = try JSONEncoder().encode(mySharedObject)
    
          /// Make sure to use your "App Group" container suite name when saving and retrieving the object from UserDefaults
          let container = UserDefaults(suiteName:"group.com.widgetTest.widgetContainer")
              container?.setValue(data, forKey: "sharedObject")
                            
          /// Used to let the widget extension to reload the timeline
          WidgetCenter.shared.reloadAllTimelines()
    
          } catch {
            print("Unable to encode WidgetDay: \(error.localizedDescription)")
       }
}

But I get the following errors.

  • Extra argument at position #1, #2 in call
  • Missing argument for parameter from call
  • insert from : <#Decoder#>
  • expected declaration where I use the do part.
submariner
  • 308
  • 1
  • 5
  • 23
  • 1
    This might help you: [Share data between main App and Widget in SwiftUI for iOS 14](https://stackoverflow.com/questions/63922032/share-data-between-main-app-and-widget-in-swiftui-for-ios-14) If it's just one variable you can use shared `UserDefaults`. And why do you need `MySharedObjects`? – pawello2222 Sep 21 '20 at 16:08
  • I have to admit that i dont understand what the person is explaining. Is he creating a text file and store the data there? – submariner Sep 21 '20 at 19:30

1 Answers1

9
  1. Save data to UserDefaults in your main App:
UserDefaults(suiteName: <your_app_group>)!.set("test", forKey: "test")
  1. Read data from UserDefaults in your Widget:
let testStr = UserDefaults(suiteName: <your_app_group>)!.string(forKey: "test")

If you want to save other types see:

pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • 1
    It worked thank you. It was much more simple than I tought. I tested it with Main app as SwiftUI and Widget as SwiftUI. I will check tomorrow if this also works with my Main app as Storyboard and Widget as SwiftUI. – submariner Sep 21 '20 at 20:03