5

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.
2
  • 1
    This might help you: 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? Commented Sep 21, 2020 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? Commented Sep 21, 2020 at 19:30

1 Answer 1

11
  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:

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.