我正在尝试通过我的按钮调用的函数而不是直接从按钮访问另一个SwiftUI View()。我知道,如果我要使用按钮,只需执行此操作
Button(action: {
self.showingDetail.toggle()
}) {
Text("Show Detail")
}.sheet(isPresented: $showingDetail) {
DetailView()
}
但是,我的按钮
Button(action: {
self.makeGetCall()
}) {
Text("LOGIN") .font(.largeTitle)
.fontWeight(.heavy)
.foregroundColor(Color.black)
}
.alert(isPresented: $showingAlert) {
Alert(title: Text("Logging Error"), message: Text("Invalid username or password."), dismissButton: .default(Text("OK.")))
}
调用需要确定要转到哪个视图的函数。
所以在makeGetCall()中,如何进入新视图?
这是makeGetCall()的当前代码
func makeGetCall() {
// Set up the URL request
let todoEndpoint: String = "https://balancingpawsdogtraining.com/api/user/generate_auth_cookie/?username=\(username)&password=\(password)"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo
// let's just print it to prove we can access it
print("The todo is: " + todo.description)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
if let status = todo["status"] as? String
{
if status == "error"
{
self.showingAlert = true
return
}
else
{
AppVariables.cookie = todo["cookie"] as! String
self.showLinkTarget = true
print("The title is \(todo["cookie"] as! String)")
MainScreenView()
}
}
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
}
我尝试过
AppVariables.cookie = todo["cookie"] as! String
self.showLinkTarget = true
print("The title is \(todo["cookie"] as! String)")
MainScreenView()
仅调用MainScreenView()---这是在这种情况下我想使用的视图的名称,但这无济于事。
那么我该如何将MainScreenView()转换为实际导航到MainScreenView()
----编辑----
我想我可以做到
}.sheet(isPresented: $showingDetail) {
MainScreenView()
}
并在我调用的函数中更改showingDetail。
但是,这将新视图“覆盖”当前视图,如何完全切换到新视图?