用Swift 3.0parsingJSON数组到Server

我想发送一个JSON数组到Web服务器。 我已经看了几个例子在线,即https://www.youtube.com/watch?v=aTj0ZLha1zE&t和保存CoreData到一个Web服务器与Swift 3.0已经演示了如何parsing数据,但我正在努力实现这一目标。

下面是我应该把数据发送到服务器的function:

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 } 

在将数据编码为JSON之后,打印出如下所示的内容:

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

然而,当我尝试parsing它,虽然到服务器,我得到这一点,没有得到发送到服务器:

responseString =可选(“”)

更新:

从这里下面的评论以下是我的posdata.php看起来像:

 <?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; } } }