问题
How to pass uiviewcontroller data to swiftui widget class i am unable to do it with app groups also write now i am sending it with userdefaults but unable to do it
if let userDefaults = UserDefaults(suiteName: "group.com.soup.ios.app") {
UserDefaults.standard.set(self.dat ?? "", forKey: "date")
UserDefaults.standard.set(self.textData.text ?? "", forKey: "text")
}
if let userDefaults = UserDefaults(suiteName: "group.com.soup.ios.app") {
let text = UserDefaults.standard.object(forKey: "text") as? String
Text(text ?? "Add Data").lineLimit(2)
.truncationMode(.middle)
}
回答1:
I managed it to do it like this and it worked
extension UserDefaults {
static let group = UserDefaults(suiteName: "group.com.your.domain")!
}
setting data:
UserDefaults.group.set("objectToShare", forKey: "keyForTheObject")
getting data:
let object = UserDefaults.group.object(forKey: "keyForTheObject")
回答2:
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!
来源:https://stackoverflow.com/questions/64240439/how-to-pass-uiviewcontroller-data-to-swiftui-widget-class