Sharing Data with AppGroup

北战南征 提交于 2020-12-26 09:06:16

问题


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.

回答1:


  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:

  • How can I use UserDefaults in Swift?


来源:https://stackoverflow.com/questions/63995776/sharing-data-with-appgroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!