当响应位于 html(Swift) 时,如何读取表单数据的内容

How can I read the content of a form-data when the response is in html(Swift)

我正在构建一个 iOS 应用程序,我需要访问网站上的信息。我找到了 API 端点,并且能够在 Postman 中获得结果 screenshot of API header and form data

到目前为止我有这段代码可以让我发出请求,但我如何解析响应(这是一个 HTML 表单,然后在应用程序中显示响应

        var urlRequest = URLRequest(url: url!)
        urlRequest.setValue("application/form-data",forHTTPHeaderField: "Content-Type")
        urlRequest.httpMethod = "POST"
        let postString = "year=2021&season=Outdoor&province=ON&age_group=OPEN&age_sub_group_masters=ALL&age_sub_group_para=ALL&rankings_event=100m&best_by_athlete=1&rankings_event_spec_num=1&is_relay_EVENT=0&page=1"
        urlRequest.httpBody = postString.data(using: .utf8)
        
        urlRequest = .init(url: url!)```

我实际上找到了一个很棒的资源,它展示了如何发送带有 post 正文的 POST 请求,以及如何读取响应

How To send POST Request

现在只需解析返回的HTML,并在应用程序中显示即可。

        let url = URL(string: Constants.rankingAPI)
        guard let requestUrl = url else {
            fatalError()
        }
        
        var request = URLRequest(url: requestUrl)
        request.httpMethod = "POST"
        
        let postString = "year=2021&season=Outdoor&province=ON&age_group=OPEN&age_sub_group_masters=ALL&age_sub_group_para=ALL&rankings_event=100m&best_by_athlete=1&rankings_event_spec_num=1&is_relay_EVENT=0&page=1"
        
        request.httpBody = postString.data(using: String.Encoding.utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            
            // Check for Error
            if let error = error {
                print("Error took place \(error)")
                return
            }
            
            // Convert HTTP Response Data to a String
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("Response data string:\n \(dataString.htmlToString)")
            }
        }
        task.resume()
    }