使用Swift在POST请求中的数组

时间:2016-04-13 17:26:12

标签: arrays json swift

我正在尝试将数组发送到PHP脚本,但我无法在服务器端检测到此数组。我创建了打印所有REQUEST数组的php脚本。对于这段代码:

 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)
    }

在Xcode控制台中我收到了

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

我做错了什么?

P.S。如果我添加.PrettyPrinted我收到:

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

我不知道 - 这个“_:_”来自哪里?

1 个答案:

答案 0 :(得分:1)

php不会自动识别出它是一个json字符串

添加以下行:

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

允许PHP知道它是一个json字符串