Search code examples
swiftgoogle-mapsswift4google-places-api

How can I solve [NSArray0 objectAtIndex:] error in Swift?


I am getting the error above when clicking on my swift app to track driver location. Essentially, it shows the driver location but fails to draw the path between the driver and hotel/customer. The app freezes and throws the error above. Hopefully, someone can help me out with this.

func makePath(){
    self.mapView.clear()
    var bounds = GMSCoordinateBounds()
    self.mapView.camera = GMSCameraPosition.camera(withLatitude: (self.riderlat as NSString).doubleValue, longitude: (self.riderlong as! NSString).doubleValue, zoom: 1.0)
    self.riderMarker.title = StaticData.singleton.map_name
    self.riderMarker.snippet = StaticData.singleton.map_phone

    let str :String?
    if (self.riderlat == "0.0" || self.riderlong == "0.0" || self.hotellat == "0.0" || self.hotellong == "0.0" ) {
        str = ""
    } else {
        str = String(format:"https://maps.googleapis.com/maps/api/directions/json?origin=\(self.riderlat!),\(self.riderlong!)&destination=\(self.hotellat!),\(self.hotellong!)&key=AIzaSyBEDFKSDFKDSFNSDKF9434-0")
        
        //print(str!)
    }
    
    Alamofire.request(str!).responseJSON { (responseObject) -> Void in
        let resJson = JSON(responseObject.result.value)
        //print(resJson)
        
        if(resJson["status"].rawString()! == "ZERO_RESULTS") {
            
        } else if(resJson["status"].rawString()! == "NOT_FOUND") {
            
        } else {
            if  let routes : NSArray = resJson["routes"].rawValue as? NSArray {
                //print(routes)

                self.mapView.isMyLocationEnabled = true
                let position = CLLocationCoordinate2D(latitude:(self.riderlat as NSString).doubleValue, longitude: (self.riderlong as NSString).doubleValue)

                let marker = GMSMarker(position: position)

                marker.icon = UIImage(named: "Car.png")
                marker.title = "Customer have selected same location as yours"
                marker.map = self.mapView
                bounds = bounds.includingCoordinate(marker.position)

                let position2 = CLLocationCoordinate2D(latitude:(self.hotellat as NSString).doubleValue, longitude: (self.hotellong as NSString).doubleValue )

                let marker1 = GMSMarker(position: position2)
                marker1.icon = UIImage(named: "HotelPin")
                marker1.appearAnimation = GMSMarkerAnimation.pop
                marker1.map = self.mapView
                self.riderMarker.icon = UIImage(named:"Car.png")
                self.riderMarker.map = self.mapView
                self.getAddressFromLatLon(pdblLatitude:StaticData.singleton.rider_lat!, withLongitude:StaticData.singleton.rider_lon!)

                for p in (0 ..< self.polyArray.count) {
                    (self.polyArray[p]).map = nil
                }
                let pathv : NSArray = routes.value(forKey: "overview_polyline") as! NSArray
                //print(pathv)
                let paths : NSArray = pathv.value(forKey: "points") as! NSArray
                //print(paths)

                let newPath = GMSPath.init(fromEncodedPath: paths[0] as! String)

                let polyLine = GMSPolyline(path: newPath)
                polyLine.strokeWidth = 5
                polyLine.strokeColor = UIColor(red:190/255.0, green:44/255.0, blue:44/255.0, alpha:1.0)
                self.polyArray.append(polyLine)
                polyLine.map = self.mapView
                self.polyArray.append(polyLine)
                let bounds = GMSCoordinateBounds(path: newPath!)
                self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 50.0))
            }
        }
    }
}

in particular it is this portion of the code in which the error is pointing towards:

let newPath = GMSPath.init(fromEncodedPath: paths[0] as! String)

Solution

  • That line of your code made an assumption that paths array always has at least one element. This error show when paths is empty, so you need to check for array is not empty first:

    let paths : NSArray = pathv.value(forKey: "points") as! NSArray
    if (paths.count == 0) {
        // Do something depend on your business or return error
    }
    let newPath = GMSPath.init(fromEncodedPath: paths[0] as! String)