问题
Hey below you find my source code. What i wanna do is:
After the Json is extracted I want that it will be accessable in a other view... Please help me...
I Mean the extracted Value: "\n (users.Name)"
So I want simply the response data into a other view...
struct User: Codable {
let Name: String
}
let url = URL(string: "http://192.168.178.26/iso/loginserv.php")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
let postString = "user=\(self.user)&pass=\(self.pass)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) {
(data, response, error) in
if let error = error {
print("Error took place \(error)")
return
}
guard let data = data else {return}
do{
let users = try JSONDecoder().decode(User.self, from: data)
print("Response data Name: \n \(users.Name)")
if !(data.isEmpty) {
self.signedIn = true
}
}catch let jsonErr{
print(jsonErr)
}
}
task.resume()
All i want is to get the marked thing into another view...
回答1:
What you could do is use Singleton design pattern.
Basically you create a class that is instanced a single time only, with a global static property. That property will be used to pass info from one view to another.
So, first create a Singleton class (as a simple Swift file) and define a static instance, like this:
class Singleton {
static let instance = Singleton()
private init() {
}
}
Now, create and initialize the variable you want to share between views, for example the string name
:
class Singleton {
static let instance = Singleton()
private init() {
}
var name = ""
}
Now, in your code, attribute users.Name
to it:
do{
let users = try JSONDecoder().decode(User.self, from: data)
print("Response data Name: \n \(users.Name)")
Singleton.instance.name = users.Name
if !(data.isEmpty) {
self.signedIn = true
}
}catch let jsonErr{
print(jsonErr)
}
Now, to access this info in another view, just use Singleton.instance.name
.
回答2:
Use a struct like this
struct structFittings {
static var collectedWorks: Bool = false
static var collected: String = "notcollected"
static var failclicked: Bool = false
}
Access like this
structFittings.collectedWorks
Any where in the app
来源:https://stackoverflow.com/questions/60028295/swiftui-passing-variable-into-antoher-view