Condivisione dei dati con AppGroup

Sep 21 2020

Voglio condividere una variabile dal mio file UIKit alla mia estensione widget creata con SwiftUI. L'ho seguito qui. Si prega di guardare la risposta di J Arango.

Ma non capisco l'ultima parte. Devo usare import MySharedObjects.

Quindi ho fatto questo:

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

Ma ottengo i seguenti errori.

  • Argomento extra alla posizione # 1, # 2 nella chiamata
  • Argomento mancante per il parametro dalla chiamata
  • inserire da: <# Decoder #>
  • dichiarazione prevista in cui utilizzo la doparte.

Risposte

2 pawello2222 Sep 21 2020 at 19:35
  1. Salva i dati UserDefaultsnella tua app principale:
UserDefaults(suiteName: <your_app_group>)!.set("test", forKey: "test")
  1. Leggi i dati dal UserDefaultstuo widget:
let testStr = UserDefaults(suiteName: <your_app_group>)!.string(forKey: "test")

Se vuoi salvare altri tipi vedi:

  • Come posso utilizzare UserDefaults in Swift?