与 AppGroup 共享数据 [英] Sharing Data with AppGroup

查看:21
本文介绍了与 AppGroup 共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个变量从我的 UIKit 文件共享到我用 SwiftUI 创建的小部件扩展.我在这里关注了这个.请看看 J Arango 的回答.

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.

但我不明白那里的最后一部分.我必须使用 import MySharedObjects.

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

所以我这样做了:

    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)")
       }
}

但我收到以下错误.

  • 调用中#1、#2位置的额外参数
  • 缺少调用参数的参数
  • 插入自:<#Decoder#>
  • 我使用 do 部分的预期声明.
  • 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. 将数据保存到主应用程序中的 UserDefaults:

UserDefaults(suiteName: <your_app_group>)!.set("test", forKey: "test")

  1. 从小部件中的 UserDefaults 读取数据:
  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:

这篇关于与 AppGroup 共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆