Swift JSON崩溃与Nil

时间:2015-06-19 11:39:22

标签: ios json swift

我有一个问题..我有一个用jSON连接数据库的应用程序,现在的问题是他无法在数据库的响应中找到该元素。 这是代码:

 func uploadtoDB(){
    var SelectVehicle = save.stringForKey("SelectVehicleChoosed")

    if SelectVehicle == nil  {

        var alertView:UIAlertView = UIAlertView()
        alertView.title = "Submit Failed!"
        alertView.message = "Please Select the Vehicle"
        alertView.delegate = self
        alertView.addButtonWithTitle("OK")
        alertView.show()


    }else {

        var post:NSString = "vechicleNumber=\(SelectVehicle)"

        NSLog("PostData: %@",post);

        var url:NSURL = NSURL(string: "http://saimobileapp.com/services/sai_service_history.php?")!

        var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
        var postLength:NSString = String( postData.length )
        var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")


        var reponseError: NSError?
        var response: NSURLResponse?

        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

        if ( urlData != nil ) {
            let res = response as! NSHTTPURLResponse!;

            NSLog("Response code: %ld", res.statusCode);

            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                NSLog("Response ==> %@", responseData);
                println(responseData)
                var error: NSError?

                let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary


                var serviceDate = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceDate"] as! String
                var serviceType = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceType"] as! String
                var kms = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["mileage"] as! String
                var serviceLocation = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceLocation"] as! String


                var serviced:Void = save.setObject(serviceDate, forKey: "ServiceDateChoosed")
                var servicet:Void = save.setObject(serviceType, forKey: "ServiceTypeChoosed")
                var kmsc:Void = save.setObject(kms, forKey: "KmsChoosed")
                var servicel:Void = save.setObject(serviceLocation, forKey: "ServiceLocationChoosed")
                              save.synchronize()

                 TableView.reloadData()

            }
        } 
    }
}

这是回复

{"serviceHistory":[{"id":"2","vehicleNumber":"mh03aw0001","mobileNumber":"9503322593","customerName":"samsun","serviceDate":"2012-06-02","serviceType":"Paid Service","mileage":"65","serviceState":"Maharashtra","serviceLocation":"Lower Parel","PUC":""}]}

应用程序在行var serviceDate = ((jsonData as NSDictionary)["serviceHistory"] as! NSDictionary) ["serviceDate"] as! String中以nil崩溃,因为我认为他无法找到该元素。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

// serviceHistory is an Array
var serviceHistoryArray = jsonData["serviceHistory"] as! NSArray

// fetch the first item...
var serviceHistoryItem = serviceHistoryArray[0] as! NSDictionary
var serviceDate = serviceHistoryItem["serviceDate"]
var serviceType = serviceHistoryItem["serviceType"]
var kms = serviceHistoryItem["mileage"]
var serviceLocation = serviceHistoryItem["serviceLocation"]

答案 1 :(得分:0)

作为旁注:解析JSON已成为快速开发人员的一个受欢迎的游乐场,因为它是一个细微的问题,在强类型语言中可能很难。一群人已经编写了用于解决这个问题的库,并且已经有很多关于这个主题的有趣讨论。一些例子:

以及对问题的一些讨论:

相关问题