2014-11-08 79 views
0

你好,我正尝试从SWIFT IOS应用程序使用JSON发送一个参数到PHP-SQL数据库。已经尝试了几个例子sycronus和asyncronus,但我没有得到它的工作。json swift ios - 发送参数到php-sql

跟上JSON参数字符串的转换为将要在对方接收的格式..

(当我在浏览器中尝试将应用程序本身没有work..but)困扰?下面是代码 - 从操场 (响应为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)") 

什么我dooing错

+0

@Nica *您的编辑是**没有帮助***。一旦你有足够的声望,你将能够做出这样的小修正,而不会混淆建议的编辑队列。但是,在达到这一点之前,请避免进行编辑,使其他部分的帖子不固定。 – APerson 2014-11-12 02:21:42

回答

0

要设置错误的Content-Type

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。

+0

Hi Shuo - 谢谢你的回答。我尝试了你的“applicaiton/json”,这可能是正确的 - 但代码仍然不起作用:-(。“响应仍然是可选的(Missing Json) – 2014-11-11 18:51:36