0

I'm trying to get my https post response into a variable called resultFormHtml before I segue into a view controller with a WebView to display the HTML in resultFormHtml variable.

With the below code I get an error on perfomSegue "UIViewController.init(coder:) must be used from main thread only"

How can I have my resultFormHtml variable not empty and segue to the next VC?

dpoHttpPost(dpoHttp: dpoHttp) { [self] (result) in
  if result == true {
    self.performSegue(withIdentifier:"rechargeDpoSegue", sender: self)
  }else{
    //do something here
  }
}

func dpoHttpPost(dpoHttp: Bool,completion:  @escaping (Bool)->()){
  let url = URL(string: self.dpoURL)!
  var request = URLRequest(url: url)
  request.httpMethod = "POST"
  request.httpBody = self.postFormHtml.data(using: .utf8)
        
  // Create the HTTP request
  let session = URLSession.shared
  let task = session.dataTask(with: request) { (data, response, error) in

    if let error = error {
      // Handle HTTP request error
      self.resultFormHtml = "<HTML><BODY>Error</HTML></BODY>"
      completion(false)
    } else if let data = data {
      // Handle HTTP request response
      self.resultFormHtml = String(data: data, encoding: .utf8)!
      print(String(data: data, encoding: .utf8)!)
      completion(true)
    } else {
      // Handle unexpected error
      self.resultFormHtml = "<HTML><BODY>Error</HTML></BODY>"
       completion(false)
    }
  }
  task.resume()
}

1 Answers1

0

Use DispatchQueue:

if let error = error {
        // Handle HTTP request error
        self.resultFormHtml = "<HTML><BODY>Error</HTML></BODY>"
        completion(false)
    } else if let data = data {
        
        DispatchQueue.main.async{ [self] in
            
            // Handle HTTP request response
            self.resultFormHtml = String(data: data, encoding: .utf8)!
            
            print(String(data: data, encoding: .utf8)!)
            
            completion(true)
            
        }
        
    } else {
        // Handle unexpected error
        self.resultFormHtml = "<HTML><BODY>Error</HTML></BODY>"
        completion(false)
    }