[SOLVED] Navigate after the post request is successful (http) in swiftui?

Issue

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

Solution

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

Answered By – Oguzhan Karakus

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.