swiftui中post请求成功(http)后导航?
我的请求是
class LoginManager : ObservableObject {
@Published var isLoggedIn = false
func LoginRequestHttp(email: String, password: String, token: String) {
// declare the parameter as a dictionary that contains string as key and value combination. considering inputs are valid
let parameters:Dictionary<String, Any> = [
"data" : [
"email" : email,
"password" : password,
"token" : token,
]
]
// create the url with URL
let url = URL(string: "myurl")! // change server url accordingly
// create the session object
let session = URLSession.shared
// now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
request.httpBody = parameters.percentEncoded()
// add headers for the request
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // change as per server requirements
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
do {
// convert parameters to Data and assign dictionary to httpBody of request
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
return
}
// create dataTask using the session object to send data to the server
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("Post Request Error: \(error.localizedDescription)")
return
}
// ensure there is valid response code returned from this HTTP response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode)
else {
print("Invalid Response received from the server")
return
}
// ensure there is data returned
guard let responseData = data else {
print("nil Data received from the server")
return
}
do {
// create json object from data or use JSONDecoder to convert to Model stuct
if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? Dictionary<String,Any>{
print(jsonResponse)
let decoder = JSONDecoder()
do {
let loginResponse = try decoder.decode(LoginResponse.self, from: responseData)
AuthenticationManager.shared.saveToken(loginResponse: loginResponse.response)
AuthenticationManager.shared.saveUid(loginResponse: loginResponse.response)
print("Users list :", loginResponse.response.uid )
print("Login Succesfull")
} catch {
print(error)
}
// handle json response
} else {
print("data maybe corrupted or in wrong format")
throw URLError(.badServerResponse)
}
} catch let error {
print(error.localizedDescription)
}
}
// perform the task
task.resume()
}
}
,我的按钮是:
Button(action: { loginManager.LoginRequestHttp(email: email, password: password, token: token)
}){
HStack(alignment: .center) {
Text("Login")
.font(.system(size: 17))
.fontWeight(.bold)
.foregroundColor(.white)
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
.background(
RoundedRectangle(cornerRadius: 25)
.fill(Color("Color"))
.shadow(color: .gray, radius: 2, x: 0, y: 2)
)
}
}
http post成功后如何导航到第二个视图,即主页视图
,我回顾了这里发布的所有问题,它们不提供我的案例的答案,我的案例是不同的,我希望您能向我展示
任何解决方案,非常感谢您的好意
my request is
class LoginManager : ObservableObject {
@Published var isLoggedIn = false
func LoginRequestHttp(email: String, password: String, token: String) {
// declare the parameter as a dictionary that contains string as key and value combination. considering inputs are valid
let parameters:Dictionary<String, Any> = [
"data" : [
"email" : email,
"password" : password,
"token" : token,
]
]
// create the url with URL
let url = URL(string: "myurl")! // change server url accordingly
// create the session object
let session = URLSession.shared
// now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
request.httpBody = parameters.percentEncoded()
// add headers for the request
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // change as per server requirements
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
do {
// convert parameters to Data and assign dictionary to httpBody of request
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
return
}
// create dataTask using the session object to send data to the server
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("Post Request Error: \(error.localizedDescription)")
return
}
// ensure there is valid response code returned from this HTTP response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode)
else {
print("Invalid Response received from the server")
return
}
// ensure there is data returned
guard let responseData = data else {
print("nil Data received from the server")
return
}
do {
// create json object from data or use JSONDecoder to convert to Model stuct
if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? Dictionary<String,Any>{
print(jsonResponse)
let decoder = JSONDecoder()
do {
let loginResponse = try decoder.decode(LoginResponse.self, from: responseData)
AuthenticationManager.shared.saveToken(loginResponse: loginResponse.response)
AuthenticationManager.shared.saveUid(loginResponse: loginResponse.response)
print("Users list :", loginResponse.response.uid )
print("Login Succesfull")
} catch {
print(error)
}
// handle json response
} else {
print("data maybe corrupted or in wrong format")
throw URLError(.badServerResponse)
}
} catch let error {
print(error.localizedDescription)
}
}
// perform the task
task.resume()
}
}
and my button is:
Button(action: { loginManager.LoginRequestHttp(email: email, password: password, token: token)
}){
HStack(alignment: .center) {
Text("Login")
.font(.system(size: 17))
.fontWeight(.bold)
.foregroundColor(.white)
.frame(minWidth: 0, maxWidth: .infinity)
.padding()
.background(
RoundedRectangle(cornerRadius: 25)
.fill(Color("Color"))
.shadow(color: .gray, radius: 2, x: 0, y: 2)
)
}
}
how to navigate for a second view which is home view once the http post is successfully
made, i reviewed all the questions posted here here they don't serve the answer for my case , my case is different , i prefer if you can show me it
any solution for this thank you alot for your kindness
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将
bool Completion
添加到您的LoginRequestHttp
方法并像这样检查
you can add
bool completion
to yourLoginRequestHttp
methodand check like this