This solution is in swift 5.
In order to pass data between targets, you need to:
- create your sharedDefaults structure
- declare your global data variable
- change the variable's data from your target\viewcontroller using support variables.
First of all create a new .swift file. Go on inspector>file>target membership and select the targets you want to comunicate.
SharedDefaults helper
//This goes in your new swift file
let sharedUserdefaults = UserDefaults(suiteName: SharedDefault.suitName)
struct SharedDefault {
static let suitName = "group.com.soup.ios.app"
struct Keys{
static let Key = "text"
}
}
Global data variable
//This goes in your new swift file
//This is an array of strings change the type by changing what's after "data:"
var data: [String] {
get {
return sharedUserdefaults?.stringArray(forKey: Key) as? [String] ?? [String]()
} set {
}
}
So what's above is a get/set variable which stores and receives the data you save/get from your widget and your parent app.
Actually saving/retrieving stuff
Now to use this stuff either in your app or target, you have to
- Declare the support variables:
var myData: [String] = [] //This is not required but if you need to display contents in real time I'd suggest you use this.
var currentData = data //Helper variable to pass data to the sharedVariable
override func viewDidLoad() {
super.viewDidLoad()
myData.append(contentsOf: data)
}
- Save stuff:
//Update both data and current data
myData.append("ok")
currentData.append("ok")
sharedUserdefaults?.set(currentData, forKey: SharedDefault.Keys.Key)
- Delete stuff:
//Update both data and current data
mydata.remove(at: 0)
currentData.remove(at: 0)
sharedUserdefaults?.set(currentData, forKey: SharedDefault.Keys.Key)
That's it!