swift 如何发送/接收JSON变量到PHP?

jjhzyzn0  于 2022-11-28  发布在  Swift
关注(0)|答案(1)|浏览(122)

我有下面的swift代码,它有一个字典,我试图把它发送到PHP。
由于PHP没有字典,我想应该将swift中的字典转换为JSON,然后将其作为JSON发送到PHP。
不过,我就是不知道该怎么做......
另外,我如何在PHP端接收它?

SWIFT代码:

func appl(_ application: UIApplication) {
    print("...........................................................")
    
    let group = DispatchGroup() // just to avoid asnc
    let mappedViewsArray = DisplayVC.viewsArray.map { ($0,1) } // To count the similirities
    let viewsArrayCount = Dictionary(mappedViewsArray, uniquingKeysWith: +) // To add the similirities
    print(viewsArrayCount)
    do {
        let encodedDictionary = try JSONEncoder().encode(viewsArrayCount) // Convert the dictionary to JSON (encode)
        
        // let jsonData = try JSONSerialization.data(withJSONObject: viewsArrayCount)
        
        
        
        let urlPath : String = "http://localhost/updateViews.php" // PHP file URL
        let url: URL = URL(string: urlPath)!
        var request = URLRequest(url: url as URL)
        request.httpMethod = "POST" // method
        // request.httpBody = encodedDictionary
        print(viewsArrayCount)
        let postString = "JSONDataEncoded=\(encodedDictionary)" // to get the passed data in PHP
        // request.httpBody = postString.data(using: String.Encoding.utf8)
        //  request.httpBody = encodedDictionary
        request.httpBody = postString.data(using: String.Encoding.utf8) // to encode the passed variable
        group.enter() // just to avoid asnc
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in defer {group.leave()}
            // just to avoid asnc
            if error != nil {
                print("Failed to update data")
            } else {
                print("Data updated")
               
                //let responseJSON = try? JSONSerialization.jsonObject(with: data!, options: [])
               // if let responseJSON = responseJSON as? [String: Any] {
                 //   print(responseJSON)
             //   }
                
            }
        }
        task.resume() // to run the task command
        group.wait() // just to avoid asnc
        
        
        
        // to print the jsonencoded
    print(String(data: encodedDictionary, encoding: .utf8)!)
    } catch {
        print("fail")
        print("Error: ", error)
    }
}

PHP代码:

<?php
    // Create connection to database
    $con=mysqli_connect("localhost","root","","");
     
    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    // $dictionary = [5:1,1:2,3:3,9:4,13:5];
    // $json = '{"5":1,"1":2,"3":3,"9":4,"13":5}';
    // $json = $con->real_escape_string($_POST['JSONDataEncoded']);
    $json = $_POST["JSONDataEncoded"];
    $updateViews = json_decode($json, true);

    foreach($updateViews as $key => $value) {

        $stmt = $con->prepare("UPDATE cars SET views = views + '".$value."' WHERE ID = '". $key ."'");

        $stmt->execute();
        echo "good";
    }

    mysqli_close($con);
?>
uz75evzq

uz75evzq1#

我已经很久没有编写Swift代码了。我不打算尝试这样做。我假设您可以将数据转换为JSON。创建如下所示的JSON:

{"5":1, "1":2, "3":3, "9":4, "13":5}

您可以使用HTTP/POST来发送代码中显示的数据。使用POST变量应该可以工作。您也可以只在主体中发送JSON,并将POST请求的内容类型编码为application/json。唯一的区别是您必须以不同的方式读取它。

// Read from post variable
$json = $_POST['JSONDataEncoded'];

直接从正文读取

$json = file_get_contents('php://input');

有了JSON之后,转换它的过程也是一样的

$data = json_decode($json, true);
foreach ($data as $key => $row ) {
    echo "$key, $row"; // just an example
}

相关问题