在上传可选值时找到nil

时间:2015-02-11 08:26:19

标签: json swift

当我创建你可以在println(数据)看到的数据输出时,我得到数据。我正在尝试从web服务获取数据。但是,为什么在将数据解析为JSON时会发生致命错误。帮助???编码帮助&建议表示赞赏。

import Foundation

protocol AuctionAPIProtocol{
    func didReceiveAPIResults(results: NSDictionary)
}

class AuctionAPI{

var delegate: AuctionAPIProtocol

init(delegate: AuctionAPIProtocol){
    self.delegate=delegate
}

func get(path:String){
    let url = NSURL(string:path)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        println("Task Completed!!!")
        if(error != nil){
            println(error.localizedDescription)
        }
        var err: NSError?
        println(data)
        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
        //var jsonResult=JSON(data!)
        if(err != nil) {
            // If there is an error parsing JSON, print it to the console
            println("JSON Error \(err!.localizedDescription)")
        }
        let results: NSArray = jsonResult["body"] as NSArray
        self.delegate.didReceiveAPIResults(jsonResult)
    })
    task.resume()
}

func searchAuctionLatestFor(){
    let urlPath = "http://xxxxxxxxxxxxx/ws/m/automobile/global/latest/search"
    get(urlPath)
}

//TODO detail func
//func latestDetail(collectionId: Int){
//   get("xxxxxxxxxxxxxxxx")
//}
}

1 个答案:

答案 0 :(得分:0)

在解开JSON之前,您没有检查错误中的jsonResult解析是否失败。尝试以下功能并查看记录的错误。

func get(path:String){
    let url = NSURL(string:path)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        if(error != nil){
            println(error.localizedDescription)
        }
        var err: NSError?
        let jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err)
        if(err != nil) {
            println("JSON Error \(err!.localizedDescription)")
        }
        else  {
            if let jsonData = jsonResult as? [String:AnyObject] {
                let results: NSArray = jsonData["body"] as NSArray
                self.delegate.didReceiveAPIResults(jsonData)
            }
        }

    })
    task.resume()
}