由于未捕获的异常“ NSRangeException”而终止应用程序。 libc ++ abi.dylib:以类型为NSException

时间:2018-09-29 14:13:09

标签: ios swift xcode location

我收到此崩溃错误:

  

MXNet2CoreML [11383:1168377]

     

***由于未捕获的异常'NSRangeException'而终止应用程序,原因:

     

***-[__ NSArray0 objectAtIndex:]:空NSArray的下标0超出范围

     

***首次抛出调用堆栈:(0x18333f164 0x182588528 0x18329a020 0x1007894bc 0x1011ef94c 0x1011b0420 0x1021412cc 0x10214128c   0x102145ea0 0x1832e7344 0x1832e4f20 0x183204c58 0x1850b0f84   0x18c95d5c4 0x1007d8894 0x182d2456c)

     

libc ++ abi.dylib:以类型未捕获的异常终止   NSException

这是完整的代码

 //Owais: - Map setup
    func resetRegion(){
        let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 5000, 5000)
        mapKit.setRegion(region, animated: true)
    }

    var myLatitude = ""
    var myLongitude = ""

    // Array of annotations
    let annotation = MKPointAnnotation()
    var places = PredictionLocationList().place
    var locationsArray = [String]()
    var ie: Int = 0
    @IBOutlet var mapKit: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let defaults = UserDefaults.standard
        let data = defaults.data(forKey: "selectedimage")
        let uiimage2 = UIImage(data: data!)
        defaults.synchronize()
        let image = uiimage2
        // imageView.image = image

        predictUsingVision(image: image!)

        let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
        swipeDown.direction = UISwipeGestureRecognizerDirection.down
        self.view.addGestureRecognizer(swipeDown)
        // Do any additional setup after loading the view.
    }
    @objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
        if let swipeGesture = gesture as? UISwipeGestureRecognizer {
            switch swipeGesture.direction {
            case UISwipeGestureRecognizerDirection.right:
                print("Swiped right")
            case UISwipeGestureRecognizerDirection.down:
                print("Swiped down")
                self.dismiss(animated: true, completion: nil)

            case UISwipeGestureRecognizerDirection.left:
                print("Swiped left")
            case UISwipeGestureRecognizerDirection.up:
                print("Swiped up")
            default:
                break
            }
        }
    }


    func predictUsingVision(image: UIImage) {
        guard let visionModel = try? VNCoreMLModel(for: model.model) else {
            fatalError("Something went wrong")
        }

        let request = VNCoreMLRequest(model: visionModel) { request, error in
            if let observations = request.results as? [VNClassificationObservation] {
                let top3 = observations.prefix(through: 2)
                    .map { ($0.identifier, Double($0.confidence)) }
                self.show(results: top3)
            }
        }

        request.imageCropAndScaleOption = .centerCrop

        let handler = VNImageRequestHandler(cgImage: image.cgImage!)
        try? handler.perform([request])
    }

    typealias Prediction = (String, Double)

    func show(results: [Prediction]) {
        var s: [String] = []
        for (i, pred) in results.enumerated() {
            let latLongArr = pred.0.components(separatedBy: "\t")
            print("lat long \(latLongArr)")
            myLatitude = latLongArr[1]
            myLongitude = latLongArr[2]

            ie = i

            s.append(String(format: "%d: %@ %@ (%.2f%%)", i + 1, myLatitude, myLongitude, pred.1 * 100))
            LocationByCoordinates(latitude: myLatitude, longitude: myLongitude)
           // let ew1 = (String(format: "%.2f%", pred.1 * 100))
           // print(ew1)
           // let double1 = Double(ew1)
           // self.doubles.append(double1!)
           // print("eueue \(self.doubles)")



            // let maxDouble = max(max(double1, double2), double3)

            print("first latidue \(myLatitude),,,, \(myLongitude)")

            places[i].title = String(i+1)
            places[i].coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(myLatitude)!, longitude: CLLocationDegrees(myLongitude)!)


        }
       // predictionLabel.text = s.joined(separator: "\n")



        // Map reset
        resetRegion()

        mapKit.centerCoordinate = places[0].coordinate
        // Show annotations for the predictions on the map

        mapKit.addAnnotations(places)
        // Zoom map to fit all annotations
        zoomMapFitAnnotations()
    }
    func zoomMapFitAnnotations() {
        var zoomRect = MKMapRectNull
        for annotation in mapKit.annotations {

            let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
            let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0)
            if (MKMapRectIsNull(zoomRect)) {
                zoomRect = pointRect
            } else {
                zoomRect = MKMapRectUnion(zoomRect, pointRect)
            }
        }
        self.mapKit.setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(50, 50, 50, 50), animated: true)
    }

    func LocationByCoordinates (latitude: String,longitude:String) {
        let mapsKey = UserDefaults.standard.string(forKey: "maps_key") ?? ""
        Alamofire.request("https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&key=\(mapsKey)").responseJSON { response in

            if let json = response.result.value {
                let request = json as? NSDictionary
                if let id = request!["results"] {
                    // print(id)
                    let ide = id as? NSArray
                    let formatted_address = ide![0]
                    let fors = formatted_address as! NSDictionary

                    //print(fors.value(forKey: "formatted_address"))
                    let forss = fors.value(forKey: "formatted_address")

                    self.locationsArray.append(forss as? String ?? "")

                    if self.ie == 0 {
                        self.places[0].identifier = (forss as? String)!
                    } else if self.ie == 1 {
                        self.places[1].identifier = (forss as? String)!
                    } else if self.ie == 2 {
                        self.places[2].identifier = (forss as? String)!
                    }

                }
            }
        }

    }
}
extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

1 个答案:

答案 0 :(得分:0)

问题出在这一行let formatted_address = ide![0]

如果数组为空,则[0]不能使它成为第一个元素,因为根本没有元素!

您要做的就是在解开数组之前检查数组是否为空:

if ide!.count > 0 {
    //Your code
}

为避免强行展开ide,您可能希望像这样使用可选绑定:

if let id = request!["results"], let ide = id as? NSArray {
    let formatted_address = ide[0]
    let fors = formatted_address as! NSDictionary
    //rest of your code
}