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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
    • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
    • ¥200 uniapp长期运行卡死问题解决
    • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
    • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
    • ¥15 乘性高斯噪声在深度学习网络中的应用
    • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
    • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集