我对Swift还是很陌生,我向php脚本创建了一个小的POST请求,该请求发布了用户输入的数据并返回了JSON响应。但是现在我正在为某些事情而苦苦挣扎。在我的动作脚本中,按钮代表打印错误或打印json响应。
但是现在我想更改它,以便转到HomeView。
我试图将HomeView()放入if语句中,但是它不起作用。
希望您能够帮助我。
import SwiftUI
struct AppRootView: View {
@State var signedIn: Bool = false
var body: some View {
Group{
if(signedIn){
HomeView()
} else {
Login()
}
}
}
}
struct ContentView: View {
var body: some View {
Login()
}
}
struct HomeView: View {
var body: some View {
Text("test")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Login : View {
@State var user = ""
@State var pass = ""
@Binding var signedIn: Bool
var body : some View {
VStack{
/*Group {
if (signedIn) {
HomeView()
} else {
Login()
}
}*/
Image("logo")
.resizable()
.frame(width: 100, height: 100)
Text("Sign In").fontWeight(.heavy).font(.largeTitle).foregroundColor(Color("Iso-Blue")).padding([.top,.bottom], 20)
VStack(alignment: .leading){
VStack(alignment: .leading){
Text("Username").font(.headline).fontWeight(.light)
HStack{
TextField("Enter Your Username", text: $user)
}
Divider()
}
VStack(alignment: .leading){
Text("Password").font(.headline).fontWeight(.light)
SecureField("Enter Your Password", text: $pass)
Divider()
}
}.padding(.horizontal, 6)
VStack{
/*if (signedIn == true) {
HomeView()
} else {
Login()
}*/
Button(action: {
let url = URL(string: "http://192.168.178.39/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
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
self.signedIn = true
}
}
task.resume()
}) {
Text("Sign In").foregroundColor(.white).frame(width: UIScreen.main.bounds.width - 120).padding()
}.background(Color("Iso-Gray"))
.clipShape(Capsule())
.padding(.top, 45)
}
}.padding()
}
}
最佳答案
为了适应swiftui的声明性,这需要一些重新思考和重写。问题是登录结构不够高。登录之前,我们需要告诉框架有关HomeView的信息。
在UIKit应用中;我们将要求用户登录,然后在成功登录后选择进入HomeView。
在SwiftUI应用中;我们声明一个RootView根据当前状态显示正确的视图。
struct AppRootView: View {
@State var signedIn: Bool = false
var body: some View {
Group {
if (signedIn) {
HomeView()
} else {
LoginView(signedIn: $signedIn)
}
}
}
}
接下来,将绑定添加到您在上面链接的loginView上。注意,我将绑定作为参数传递给loginView。
struct LoginView: View {
@Binding var signedIn: Bool
...
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
signedIn = true
}
...
}