在包装可选值时发现nil [英] Found nil while upwrapping an Optional value

查看:116
本文介绍了在包装可选值时发现nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When i create output of data which you can see at println(data),i get the data.I am trying to get the data from web service.But,why the fatal error occur when parsing the data to JSON.Any help???coding help & suggestion is appreciated.

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")
//}
}

推荐答案

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

You are not checking if the JSON parsing has failed in the error before unwrapping the jsonResult. Try the following function and see the logged errors.

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()
}

这篇关于在包装可选值时发现nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆