如果没有收到数据,则抛出异常

时间:2016-06-02 21:02:32

标签: ios swift nsarray optional

我正在使用以下Class从外部数据库接收数据:

import Foundation

protocol HomeModelProtocal: class {
    func itemsDownloaded(items: NSArray)
}


class HomeModel: NSObject, NSURLSessionDataDelegate {

    //properties

    weak var delegate: HomeModelProtocal!

    var data : NSMutableData = NSMutableData()

    var mi_movil: String = ""

    let misDatos:NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var urlPath: String = "http:...hidden here.."
    let parametros = "?id="

    func downloadItems() {

        mi_movil = misDatos.stringForKey("ID_IPHONE")!
        print ("mi_movil en HOMEMODEL:",mi_movil)
         urlPath = urlPath + parametros + mi_movil

        let url: NSURL = NSURL(string: urlPath)!
        var session: NSURLSession!
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()

        print ("LA URL ES: ",url)
        session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

        let task = session.dataTaskWithURL(url)

        task.resume()

    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        self.data.appendData(data);

    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        if error != nil {
            print("Failed to download data")
        }else {
            print("Data downloaded")
            self.parseJSON()

        }

    }

    func parseJSON() {


        var jsonResult: NSMutableArray = NSMutableArray()

        do{




            jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray

        } catch let error as NSError {
            print(error)

        }

        var jsonElement: NSDictionary = NSDictionary()
        let locations: NSMutableArray = NSMutableArray()


        for(var i = 0; i < jsonResult.count; i++)
        {

            jsonElement = jsonResult[i] as! NSDictionary
            print (jsonElement)
            let location = MiAutoModel()

            //the following insures none of the JsonElement values are nil through optional binding
            if let id_mis_autos = jsonElement["id_mis_autos"] as? String,
                let modelo = jsonElement["modelo"] as? String,
                let ano = jsonElement["ano"] as? String,
                let id_movil = jsonElement["id_movil"] as? String
            {

                location.id_mis_autos = id_mis_autos
                location.modelo = modelo
                location.ano = ano
                location.id_movil = id_movil

            }

            locations.addObject(location)

        }

        dispatch_async(dispatch_get_main_queue(), { () -> Void in

            self.delegate.itemsDownloaded(locations)

        })
    }
}

如果收到数据,它可以正常工作但如果没有数据则抛出异常:

  

无法将'__NSArray0'(0x1a0dd2978)类型的值转换为'NSMutableArray'(0x1a0dd3490)

我应该更改什么来检测是否没有数据来避免异常?

2 个答案:

答案 0 :(得分:2)

由于您似乎无法在任何地方修改jsonResult,因此显而易见的选择是将其设为NSArray而不是NSMutableArray,并更改向下广播以匹配该广告。{ / p>

答案 1 :(得分:1)

我不确定你为什么要使用NSDictionaryNSMutableArray,但我会这样做:

for result in jsonResult {

    guard let jsonElement = result as? [String:AnyObject] else { return }
    let locations: [MiAutoModel] = []

    let location = MiAutoModel()

    //the following insures none of the JsonElement values are nil through optional binding
    let id_mis_autos = jsonElement["id_mis_autos"] as? String ?? ""
    let modelo = jsonElement["modelo"] as? String ?? ""
    let ano = jsonElement["ano"] as? String ?? ""
    let id_movil = jsonElement["id_movil"] as? String ?? ""

    location.id_mis_autos = id_mis_autos
    location.modelo = modelo
    location.ano = ano
    location.id_movil = id_movil

    locations.append(location)

}

您可能需要根据具体情况更改部分代码。