在swiftui中发帖请求成功(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帖子成功,如何导航到主视图的第二个视图

做了,我审查了这里发布的所有问题,它们不适合我的情况,我的情况不同,我更喜欢你能给我看

对此有任何解决方案吗?谢谢你的好意

您可以将bool completion添加到LoginRequestHttp方法中

class LoginManager : ObservableObject {
@Published var isLoggedIn = false
func LoginRequestHttp(email: String, password: String, token: String, completion: ((Bool) -> Void)? = nil) {
// 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)")
//here
completion?(false)
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")
//here
completion?(false)
return
}

// ensure there is data returned
guard let responseData = data else {
print("nil Data received from the server")
//here
completion?(false)
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")
//here
completion?(true)
} catch {
//here
completion?(false)
print(error)
}
// handle json response
} else {
print("data maybe corrupted or in wrong format")
//here
completion?(false)
throw URLError(.badServerResponse)
}
} catch let error {
//here
completion?(false)
print(error.localizedDescription)
}
}
// perform the task
task.resume()
}
}

像这样检查

Button(action: { loginManager.LoginRequestHttp(email: email, password: password, token: token) { isSuccess in
DispatchQueue.main.async {
if isSuccess {
// do some stuff
} else {
// handle failure case
}
}
}

}){
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)

)

}
}

最新更新