How do I decode HTML data with Swiftsoup into a struct and print that said struct?

86 Views Asked by At

I am trying to create a Network Manager which firstly requests a GET request to a aspx login form. In order to perform a login obviously I need to later on put a POST with a username/password but also a ViewState and ViewState Generator. I am trying to extract the last two named variables and I would like to store them in a Struct. I'm quite stuck on the last step.

Below you can find a code snipped:

NetworkingManager.swift:

final class NetworkingManager {
    
    static let shared = NetworkingManager()
  
    private init() {}
    
    func request(_ absoluteURL: String) {
        
        
        let url = URL(string: "https://examplelink.com")
        let request = URLRequest(url: url!)
        
        let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
            
            if error != nil { return }
            
            guard let response = response as? HTTPURLResponse,
                  (200...300) ~= response.statusCode else { return }
            
            guard let data = data else { return }
            
            do {
                let tempHTML = String(data: data, encoding: .utf8)
                let viewState = try! SwiftSoup.parse(tempHTML!).select("input[name=__VIEWSTATE]").attr("value")
                let viewStateGenerator = try! SwiftSoup.parse(tempHTML!).select("input[name=__VIEWSTATEGENERATOR").attr("value")
                
                var tokens = viewstateToken(viewState: viewState, viewStateGenerator: viewStateGenerator)
    
            } catch {
                print(error)
            }
           
        }
        dataTask.resume()
        
    }
}

viewStateToken.swift:

struct viewstateToken: Identifiable, Hashable, Codable {

    let id = UUID()
    var viewState: String
    var viewStateGenerator: String
    
}

I got through that I am able to get the variables I need and I am able to store them into viewStateToken struct, however when I try to print what is in the struct I am unable to.

This is on my ContentView when the code runs:

 .onAppear {
            NetworkingManager.shared.request("https://examplelink.com")
            
        }

Inside the onAppear I would like to print the viewstatetoken data in order to verify that there indeed is data stored and useable later on in the POST request.

0

There are 0 best solutions below