当我使用Swift通过POST JSON向服务器提供数据时,我会收到致命的错误:
在解包可选值时意外地发现了nil。
我不确定我是否传递JSON库字典,或者在发送到服务器时是否有问题,因为我无权查看服务器PHP代码。
我不知道如何
NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as! NSArray
的工作原理。
我用
创建我的JSON字典func parseExportDB() -> [AnyObject]{
var exportDict: [AnyObject] = []
for tuple in export {
var dictObj = [
"PhoneID": "petrjanata",
"LocLabel": tuple[crosslocation],
"Latitude": "123",
"Longitude": "-123",
"time" : tuple[time],
"heading" : tuple[heading]
]
exportDict.append(dictObj)
println(dictObj)
}
return exportDict
}
我接受exportDict
JSON数组对象并传入此函数:
func sendJsonToServer(ExportList: AnyObject){
var request = NSMutableURLRequest(URL: NSURL(string: "http://atonal.ucdavis.edu/geomus/submit_data.php")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
if let serializedData = NSJSONSerialization.dataWithJSONObject(ExportList, 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?
let jsonString = self.JSONStringify(ExportList)
println(jsonString)
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()
}
代码输入致命错误:
在解包可选值时意外发现nil
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as! NSArray
有错误
我不确定如何解决,或者JSON格式或服务器到底出了什么问题?