如何在Swift中将HTTP POST请求发送到JSON?

时间:2019-06-06 06:23:39

标签: json swift

如何修改此提取JSON函数以允许发送HTTP POST请求。我已经在php中编写了一个脚本,用于查找变量“ a”

这是php的样子:

<?php


$con=mysqli_connect("localhost","username","password","dbname");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$nameValue = $_POST['a'];


$sql = "SELECT customer, FROM TABLE1 WHERE (customer = '$nameValue') and status = 'Active' ";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);


}

?>

以下是我用来检索JSON数据的Swift代码,但是现在我想响应JSON POST请求,可以在其中添加什么?

fileprivate func fetchJSON(){
    let urlString = "https://www.example.com/example/example.php"
    guard let url = URL(string: urlString) else { return }
    URLSession.shared.dataTask(with: url) { (data, _, error) in
        DispatchQueue.main.async {
            if let error = error {
                print("Failed to fetch data from url", error)
                return
            }
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                // Swift 4.1

                self.structure = try decoder.decode([ScheduleStructure].self, from: data)

                self.tableView.reloadData()

            } catch let jsonError {
                print("Failed to decode json", jsonError)
            }

        }
        }.resume()
}

0 个答案:

没有答案