swiftui中post请求成功(http)后导航?

发布于 2025-01-15 16:30:39 字数 4516 浏览 1 评论 0原文

我的请求是

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若水般的淡然安静女子 2025-01-22 16:30:39

您可以将 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)
                              
                          )
                      
                  }
              }

you can add bool completion to your LoginRequestHttp method

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

and check like this

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文