1

I looked to many materials and used lots of way sending json data to php server. First I am creating order of singleORder and collecting it in arrayOfOrders :

func createOrderInArray(){

    var savedDataHourly: NSDictionary
    var savedDataTransfer:NSDictionary
    var savedDataReis: NSDictionary
    var singleOrderClass = Order()
    //localArrayOfOrder = []

    singleOrderClass.type_id = singleStructDataOfCar.typeID
    singleOrderClass.model_id = singleStructDataOfCar.modelID

    // loading hourly
    if Load.dictionary("ServiceByHours") != nil {
         savedDataHourly = Load.dictionary("ServiceByHours")
        println("loading hourly")
        singleOrderClass.hourly.addressOfRequest = savedDataHourly["ServiceByHoursAddressOFRequest"] as String
        singleOrderClass.hourly.addressOfDelivery = savedDataHourly["ServiceByHoursAddressOfDelivery"] as String
        singleOrderClass.hourly.detailedText = savedDataHourly["ServiceByHoursDetailText"] as String
        singleOrderClass.hourly.startofWork = savedDataHourly["StartDate"] as String
        singleOrderClass.hourly.endOfWork = savedDataHourly["EndDate"] as String
        singleOrderClass.hourly.undefinedTime = savedDataHourly["undefinedTime"] as String

    }else{
        println("hourly is empty")
        singleOrderClass.hourly.addressOfRequest = ""
        singleOrderClass.hourly.addressOfDelivery = ""
        singleOrderClass.hourly.detailedText = ""
        singleOrderClass.hourly.startofWork = ""
        singleOrderClass.hourly.endOfWork = ""
        singleOrderClass.hourly.undefinedTime = ""
    }
    // loading transfer
    if Load.dictionary("ServiceByTransfer") != nil {
        savedDataTransfer = Load.dictionary("ServiceByTransfer")
        singleOrderClass.transfer.startofWork = savedDataTransfer["ServiceDataStartDate"] as String
        singleOrderClass.transfer.addressOfRequest = savedDataTransfer["ServiceDataAddressOfReq"] as String
        singleOrderClass.transfer.addressOfDelivery = savedDataTransfer["ServiceDataAddressOfDel"] as String
        singleOrderClass.transfer.detailedText = savedDataTransfer["ServiceDataDetailedText"] as String

    }else{
        singleOrderClass.transfer.startofWork = ""
        singleOrderClass.transfer.addressOfRequest = ""
        singleOrderClass.transfer.addressOfDelivery = ""
        singleOrderClass.transfer.detailedText = ""
    }
    // loading reis
    if Load.dictionary("ServiceByReis") != nil {
        savedDataReis = Load.dictionary("ServiceByReis")
        singleOrderClass.custom.startofWork = savedDataReis["ServiceDataStartDate"] as String
        singleOrderClass.custom.addressOfRequest = savedDataReis["ServiceDataAddressOfReq"] as String
        singleOrderClass.custom.addressOfDelivery = savedDataReis["ServiceDataAddressOfDel"] as String
        singleOrderClass.custom.detailedText = savedDataReis["ServiceDataDetailedText"] as String
        singleOrderClass.custom.priceProposed = savedDataReis["ServiceDataPrice"] as String
    }else{
        singleOrderClass.custom.startofWork = ""
        singleOrderClass.custom.addressOfRequest = ""
        singleOrderClass.custom.addressOfDelivery = ""
        singleOrderClass.custom.detailedText = ""
        singleOrderClass.custom.priceProposed = ""
    }

    // add this single order to array

    arrayOfOrders.append(singleOrderClass)

}

I am just collecting all orders in one array. The next step is to convert all data in array to Dictionary so I can Serialized it into json format:

func createJsonFromArrayToDict(orders: [Order])->[AnyObject]{

    //as Dictionary<String, String>
    var dictOfOrders: [AnyObject] = []
    var counter = 0

    for singleOrder in orders {
        counter = counter + 1
        println("COUNTER: \(counter)")

        var dicOfOrder = [
            "type_id": singleOrder.type_id,
            "model_id": singleOrder.model_id,
            "transfer": [
                "StartDate": singleOrder.transfer.startofWork,
                "StartPoint": singleOrder.transfer.addressOfRequest,
                "EndPoint": singleOrder.transfer.addressOfDelivery,
                "CommentText": singleOrder.transfer.detailedText
            ],
            "hourly": [
                "StartDate": singleOrder.hourly.startofWork,
                "EndDate": singleOrder.hourly.endOfWork,
                "StartPoint": singleOrder.hourly.addressOfRequest,
                "EndPoint": singleOrder.hourly.addressOfDelivery,
                "CommentText": singleOrder.hourly.detailedText,
                "Undefined_Time": singleOrder.hourly.undefinedTime
            ],
            "custom":[
                "StartDate": singleOrder.custom.startofWork,
                "StartPoint": singleOrder.custom.addressOfRequest,
                "EndPoint": singleOrder.custom.addressOfDelivery,
                "CommentText": singleOrder.custom.detailedText,
                "customPrice": singleOrder.custom.priceProposed
            ],
            "device_name": "ios_device"
        ]
        // check if it is not the same order as previous (need to include this in future)
        dictOfOrders.append(dicOfOrder)

    }

    return dictOfOrders
}

Now I am sending this JSON to server using this function:

func sendJsonToServer(OrderList: AnyObject){
var request = NSMutableURLRequest(URL: NSURL(string: "osc.kz/ru/test")!)

    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var err: NSError?
if let serializedData = NSJSONSerialization.dataWithJSONObject(OrderList, options: nil, error: &err){
    request.HTTPBody = serializedData
    println(request.HTTPBody)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")


    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        println("Response: \(response)")
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Body: \(strData)")
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as NSArray
        // var json = noWrappedJson!
        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: '\(jsonStr)'")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            for singleCode in json {
                if let parseJSON = singleCode as? NSDictionary {
                    // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                    var success = parseJSON["code"] as? String
                    println("Succes: \(success)")
                }
                else {
                    // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                    let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                    println("Error could not parse JSON: \(jsonStr)")
                }
            }
        }

    })

    task.resume()
}

However, My server is getting empty array []. I couldnt figure out why am I sending empty value. Before sending request I printed request.httpbody. It has a value, but the server get [] . Any suggestion is appreciated!

The server side is on PHP:

<?php
 if ($_REQUEST)
{   $_ARR = $_REQUEST;
$OrderList = $_ARR['OrderList'];
foreach($OrderList as $order){
 $auto_type_id = $order['type_id'];


$auto_model_id = $order['model_id'];



$device_name = $order['device_name'];
   $commentText = $order['commentText'];


 $transfer = '';
   $hourly = '';
   $custom = '';
   if (!empty($order['transfer'])) {
    $transfer = $order['transfer'];
    $db->query("insert into table_test_android set json_text = 'transfer' ");
    $db->query("insert into table_test_android set json_text = 'type:".$auto_type_id.",model_id:".$auto_model_id.",device:".$device_name."' ");
   }
   if (!empty($order['hourly'])) {
    $hourly = $order['hourly'];
    $db->query("insert into table_test_android set json_text = 'hourly' ");
    $db->query("insert into table_test_android set json_text = 'type:".$auto_type_id.",model_id:".$auto_model_id.",device:".$device_name."' ");
   }
   if (!empty($order['custom'])) {
    $custom = $order['custom'];
    $db->query("insert into table_test_android set json_text = 'custom' ");
    $db->query("insert into table_test_android set json_text = 'type:".$auto_type_id.",model_id:".$auto_model_id.",device:".$device_name."' ");
   }

  }

  $db->query("insert into table_test_android set json_text = '".json_encode($_ARR)."'");
  $code_my = mt_rand(100000, 999999);
  $code[] = array('code'=>(string)$code_my);echo json_encode($code);
 }
3
  • Please show how you are attempting to retrieve the data on your server, eg the php Commented Apr 10, 2015 at 10:37
  • I added the server side Commented Apr 10, 2015 at 10:55
  • Incidentally, this line is redundant and probably a bad idea: $_ARR = $_REQUEST. Redundant, because you copy the variable, access one element of it, and then discard it. Probably a bad idea, because the $_UPPERCASE format makes it look like a reserved superglobal, but actually it's just a normal local variable, so it's misleading to future readers of the code (e.g. you in a few months time debugging it). Commented Apr 10, 2015 at 11:09

2 Answers 2

2

If you are sending json data, phps superglobals will not be populated - to access the json you need to access the raw input stream:

$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

$OrderList = $array['OrderList'];
//provided your json is structured correctly everything else should work from here on

EDIT You probably have a number of other problems, for a start your sql is wrong - INSERT syntax looks like 'INSTERT into tablename (colname, anothercolname) VALUES (val,val);' Whereas you have a weird inset/update mashup, but this is beyond the scope of this question (how to send json data to server)

Sign up to request clarification or add additional context in comments.

1 Comment

@YestayMuratov Well, if your request body has the correct data in it, then yes i presume client side is fine - i am not experienced enough in swift (or objective-c) to answer that fully. Did you try the php i suggested?
0

Though the above answer works but as much as you can stay away from "php://input" the better for you. If you want to send an array of data [String : Any] to a php API i recommend doing the following:

  1. Populate the Array [String : Any].

  2. Convert the array to Data using JSONSerialization:

    JSONSerialization.data(withJSONObject: array, options: [])

  3. Create a URLRequest and set method to POST:

    var request = URLRequest(url: url)

  4. Create a string variable parameter example:

    let parameter = "postData=" + data.base64EncodedString() //(data variable is from step 2)

  5. In the URLRequest variable (request), populate the httpBody, example:

    request.httpBody = parameter.data(using: String.Encoding.utf8)

  6. Send the request using URLSession.shared.dataTask ...

in PHP, catch the post using $_POST["postData"], then decode the value of the post parameter using base64_decode which gives you a string representation of the json, after that you can use json_decode() to transform it into an associated array, see below:

$content = $_POST["postData"];
$decodedContent = base64_decode($content);
$json = json_decode($decodedContent, true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.