2

I am trying to send array to PHP script, but i can't detect this array on server side. I create php script that prints all REQUEST array. And for this code:

 let mapDict = [ "var1":"First", "var2":"Second"]

    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(mapDict, options: [])


        // create post request
        let url = NSURL(string: myURL)!
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"

        // insert json data to the request
        request.HTTPBody = jsonData



        let task =  NSURLSession.sharedSession().dataTaskWithRequest(request){

            data,response,error in

            if error != nil{
                print(error!.localizedDescription)
                return
            }


            let newData = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print(newData)

        }

        task.resume()
    }
    catch {
        print (error)
    }

In Xcode console I receive

Optional(Array
(
    [{"var1":"First","var2":"Second"}] => 
)

What am i doing wrong?

p.s. if i add .PrettyPrinted i receive:

Optional(Array
(
[{
__"var1"_:_"First",
__"var2"_:_"Second"
}] => 
)

And i don't know - where are this "_:_" came from?

1 Answer 1

1

The php won't auto recognize that it's a json string

add this lines:

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

allowing the PHP know it's a json string

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

3 Comments

it returns empty array if i add this code after request.HTTPMethod = "POST"
@moonvader What swift version are you using? I think you should check how does your php gets the data, it has to know that it's JSON
I use Swift 2. Maybe array can be sent without JSON?

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.