douzha6055 2017-09-21 11:25
浏览 114

使用Swift 3.0将JSON数组解析为服务器

I am trying to send a JSON array to the web server. I have looked at several examples online i.e. https://www.youtube.com/watch?v=aTj0ZLha1zE&t and Saving CoreData to a Web Server with Swift 3.0 that have demonstrated how to parse data but I am struggling to achieve this.

Below is my function which should send the data to the server:

func sendRecordToServer() -> [Record] {

        let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"Record")
        fetchRequest.resultType = .dictionaryResultType
        do {
            let records = try context.fetch(fetchRequest)

            if let jsonData = try? JSONSerialization.data(withJSONObject: records, options: []) {
                // jsonData is a byte sequence, to view it you would need to convert to string
                print(String(bytes: jsonData, encoding: String.Encoding.utf8))

                let URL_SAVE_DATA = URL(string: "http://localhost/api/postdata.php")
                let request = NSMutableURLRequest(url: URL_SAVE_DATA!)

                request.httpMethod = "POST"
                request.httpBody = jsonData

                let task = URLSession.shared.dataTask(with: request as URLRequest){
                    data, response, error in

                    guard let data = data, error == nil else {
                        // check for fundamental networking error
                        print("error=\(String(describing: error?.localizedDescription))")
                        return
                    }

                    let responseString = String(data: data, encoding: .utf8)
                    print("responseString = \(String(describing: responseString))")
                }
                task.resume()
            }

        } catch {
            print("Error fetching data from CoreData")
        }
        return records
    }

After encoding the data to JSON, it prints out like this:

Optional([["record_id": 8EC9C1C9-7DD4-4343-B7CC-E4615FDDA150, "name": John ], ["record_id": 7EEA551D-9432-4737-99FB-6BFCF3A92D21, "name": Fred Smith]])

However as I try parsing it though to the server I get this and nothing get sent to the server:

responseString = Optional("")

Update:

Following up from the comment below here is what my posdata.php looks like:

<?php

//creating response array

$json = file_get_contents('php://input');
//echo $json shoulkd show the json string

$array = json_decode($json, true);
// var_dump($arr) should show the array structure

$response = array();

if($_SERVER['REQUEST_METHOD']=='POST'){

    //getting values
    $record_id = $_POST['record_id'];
    $name = $_POST['name'];




    //including the db operation file
    require_once '../includes/DbOperation.php';

    $db = new DbOperation();

    //inserting values
    if($db->createTeam($record_id, $name)){
        $response['error']=false;
        $response['message']='Record added successfully';
    }else{

        $response['error']=true;
        $response['message']='Could not add record';
    }

}else{
    $response['error']=true;
    $response['message']='You are not authorized';
}
echo json_encode($response);

DBOperation:

<?php

class DbOperation
{
    private $conn;

    //Constructor
    function __construct()
    {
        require_once dirname(__FILE__) . '/Config.php';
        require_once dirname(__FILE__) . '/DbConnect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    //Function to create a new user
    public function createTeam($record_id, $name)
    {
        $stmt = $this->conn->prepare("INSERT INTO record (record_id, name) values (?, ?)");
        $stmt->bind_param("si", $record_id, $name);
        $result = $stmt->execute();
        $stmt->close();
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line