json swift ios - 将参数发送到php-sql

时间:2014-11-08 20:02:57

标签: php ios json swift

您好我正在尝试使用JSON将一些参数从SWIFT IOS应用程序发送到PHP-SQL数据库。已经尝试了几个sycronus和asyncronus的例子,但是我没有让它起作用。

将JSON参数字符串转换为将在另一方接收的格式时遇到麻烦..(当我在浏览器中尝试它时,它将起作用..但不是来自应用程序本身)

这是代码 - 来自PLAYGROUND (响应是API响应:可选(缺少JSON)

// Playground - noun: a place where people can play

import UIKit
import CoreLocation
var str = "Hello, playground debug use of JSON and PHP"
import Foundation


let url = NSURL(string:"http://mywebserver-replaced.no/POSITION/update.php?")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"

// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)

// set data
var dataString = " "
dataString = "json={\"FBID\":10,\"Driving\":1,\"Latitude\":\"68.123\",\"Longitude\":\"22.124\",\"Time\":\"18:24\",\"Date\":\"07.10.2014\",\"Heading\":90}"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData

println("\(requestBodyData)")  // This will print "Optional(<6a736f6e...and so on..
                               // And except the optional it is quite correct.. json={

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

// set content length
// NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)

var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
println("API Response: \(results)")

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您设置错误的内容类型

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

应该是

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

dataString = "json={\"FBID\":10,\"Driving\":1,\"Latitude\":\"68.123\",\"Longitude\":\"22.124\",\"Time\":\"18:24\",\"Date\":\"07.10.2014\",\"Heading\":90}"

删除json =,这使得主体不是有效的json。