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

标签 ios swift nsarray option-type

我正在使用以下 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)

        })
    }
}

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

Could not cast value of type '__NSArray0' (0x1a0dd2978) to 'NSMutableArray' (0x1a0dd3490)

如果没有数据,我应该更改什么来检测以避免异常?

最佳答案

由于您似乎没有在任何地方修改 jsonResult,因此显而易见的选择是将其设为 NSArray 而不是 NSMutableArray,并更改向下转换以匹配它。

关于ios - 如果没有收到数据则抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37602056/

相关文章:

ios - 通过 iPhone SDK 创建 FB Open Graph 对象

ios - 如何快速查找自定义对象数组中某个键的所有对象的总和

objective-c - 我应该总是检查 [[NSArray alloc] init ...] 是否返回 nil 吗?

ios - Firebase .observeSingleEvent(:with:) method is retrieving cached/old data

ios - ARKit 平面,上面有现实世界的物体

ios - Xcode 7.3 错误 : could not attach to pid :"983"

ios - UICollectionView 每 x 个单元格有不同的单元格

ios - 使用 iOS13 使用 NFC 读取 eID 信息时遇到问题

ios - 以相同的 Alpha 混合 Metal

iphone - 如何按字母顺序重新排列 NSArray 的元素(NSString)?