-1
[["The Cheesecake Factory", 3.8], ["Dave & Buster\'s", 3.8], ["Paul Martin\'s American Grill", 4.2], ["Yard House", 4.3], ["Javier\'s Restaurant - Irvine", 4], ["CUCINA enoteca Irvine", 4.4], ["SUBWAY®Restaurants", 3.2], ["SUBWAY®Restaurants", 4], ["Wendy\'s", 3.8], ["Izakaya Wasa", 3.7], ["Veggie Grill", 4.5], ["Bruegger\'s Bagels", 4.5], ["Capital Seafood Restaurant - Irvine Spectrum", 4], ["Burger King", 3.5], ["SUBWAY®Restaurants", 2.6], ["Corner Bakery Cafe", 3.9], ["Taiko Japanese Restaurant", 4.3], ["Red Robin Gourmet Burgers", 3.7], ["Johnny Rockets", 2.9], ["Chipotle Mexican Grill", 4]] 

20 

2017-11-15 13:26:36.367072-0800 E-Bike App[2584:1830704] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray' 
*** First throw call stack: 
(0x183ef5d04 0x183144528 0x183e510c4 0x102debe4c 0x102cafc84 0x184480f94 0x1844983b4 0x1848c1310 0x1848019e4 0x1847f1620 0x10532545c 0x105331b74 0x10532545c 0x105331b74 0x105331a34 0x1848c2fe8 0x10532545c 0x105332800 0x10533109c 0x105336b54 0x105336880 0x183b1f120 0x183b1ec20) 
libc++abi.dylib: terminating with uncaught exception of type NSException' 

Sobald ich der Ort Name, Bewertung und Ort (CLLocationCoordinate2D) oben und speichern in der Doppel-Array und Index und Ort zu analysieren, drawPolylineAmongMultiplePoints Funktion, um die Entfernung und Dauer zu finden und an das Doppel-Array anhängen oder schieben. NSRangeException ist keep poping up ..'NSRangeException', Grund: [__NSArray0 objectAtIndex:]: Index 0 über Grenzen für leere NSArray -> es ist halten von Indexgrenzen immer

Wer hat eine gute Idee, das zu lösen?

func drawPolylineAmongMultiplePoints(coordinate: CLLocationCoordinate2D, pinPoint: Int) { 

    guard let lat = mapView.myLocation?.coordinate.latitude else {return} 
    guard let long = mapView.myLocation?.coordinate.longitude else {return} 

    let aPointCoordinate = "\(lat),\(long)" 

    let bPointCoordinate = "\(coordinate.latitude),\(coordinate.longitude)" 

    let url = "http://maps.googleapis.com/maps/api/directions/json?origin=\(aPointCoordinate)&destination=\(bPointCoordinate)&sensor=false&mode=\(DrivingMode.DRIVING)" 

    guard let urlString = URL(string: url) else { 
     print("Error: Cannot create URL") 
     return 
    } 

    let urlRequest = URLRequest(url: urlString) 


    // Set up the session 

    let config = URLSessionConfiguration.default 
    let session = URLSession(configuration: config) 

    // Make the request 


    let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in 

     do{ 

      if error != nil{ 
       print("Error: \(String(describing: error?.localizedDescription))") 

      } else { 

       guard let data = data else { 
        throw JSONError.NoData 
       } 
       guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else { 
        throw JSONError.ConversionFailed 
       } 



       let arrayRoutes = json["routes"] as! NSArray 
       let dicOfPoints = arrayRoutes[0] as! NSDictionary 
       let dic1 = dicOfPoints["overview_polyline"] as! NSDictionary 
       let points = dic1["points"] as! String 

       let arrayLegs = (arrayRoutes[0] as! NSDictionary).object(forKey: "legs") as! NSArray 
       let arraySteps = arrayLegs[0] as! NSDictionary 


       let dicDistance = arraySteps["distance"] as! NSDictionary 
       let totalDistance = dicDistance["text"] as! String 
       self.totalremainingDistance = (dicDistance["value"] as! Double)*(1/1000)*(1.61) 


       let dicDuration = arraySteps["duration"] as! NSDictionary 
       let totalDuration = dicDuration["text"] as! String 
       self.totalremainingDuration = dicDuration["value"] as! Double 


       let position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude) 

       //self.eachCarouselDataDic[index] += [totalDistance, totalDuration] 

       //print(self.eachCarouselDataDic) 
       self.eachCarouselDataDic[pinPoint] += [totalDistance, totalDuration, points, position] 
       //print(self.eachCarouselDataDic) 


      } 

     }catch let error as JSONError { 
      print(error.rawValue) 
     }catch let error as NSError { 
      print(error.debugDescription) 

     } 


    }) 
    task.resume() 

} 



@objc func POIForPlaces(sender: UIButton) { 
    print("I am here~~~") 

    //mapView.clear() 

    //For Carousel view to have access to the POI elements 
    isThisFirstTime = false 
    self.eachCarouselDataDic.removeAll() 

    var typeOfPlace = String() 

    var markerImage = UIImage() 


    switch sender.tag { 
    case 0: 
     typeOfPlace = "cafe" 
     markerImage = UIImage(named: "cafe")! 
    case 1: 
     typeOfPlace = "restaurant" 
     markerImage = UIImage(named: "restaurant")! 
    default: 
     break 
    } 
    let markerView = UIImageView(image: markerImage) 


    guard let lat = mapView.myLocation?.coordinate.latitude else {return} 
    guard let long = mapView.myLocation?.coordinate.longitude else {return} 


    var arrayOfLocations = [CLLocationCoordinate2D()] 
    arrayOfLocations.removeFirst() 
    var arrayOfNames = [String()] 
    arrayOfNames.removeFirst() 
    var arrayOfAddress = [String()] 
    arrayOfAddress.removeFirst() 
    var arrayOfRating = [Double()] 
    arrayOfRating.removeFirst() 
    var name = String() 
    var counter = 0 

    let jsonURLString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(lat),\(long)&maxprice=3&radius=3200&opennow&type=\(typeOfPlace)&key=\(Config.GOOGLE_API_KEY)" 


    guard let urlString = URL(string: jsonURLString) else { 
     print("Error: Cannot create URL") 
     return 
    } 


    //markerView.tintColor = UIColor.DTIBlue() 

    let urlRequest = URLRequest(url: urlString) 


    // Set up the session 

    let config = URLSessionConfiguration.default 
    let session = URLSession(configuration: config) 


    let task = session.dataTask(with: urlRequest) { (data, response, error) in 


     guard let httpResponse = response as? HTTPURLResponse else { return } 

     switch httpResponse.statusCode { 
     case 200: 
      do{ 

       guard let data = data else { return } 

       guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary else { return } 

       //print(json) 

       DispatchQueue.global(qos: .background).async { 

        let arrayPlaces = json["results"] as! NSArray 

        if arrayPlaces.count > 0 { 
         for i in 0..<arrayPlaces.count { 
          print("-----------------------------------------------------------------------------------------------------") 

          print(arrayPlaces.count) 

          print("-----------------------------------------------------------------------------------------------------") 

          self.eachCarouselDataDic.append([]) 
          let arrayForLocations = (((arrayPlaces[i] as! NSDictionary).object(forKey: "geometry") as! NSDictionary).object(forKey: "location") as! NSDictionary) 
          let lat = arrayForLocations.object(forKey: "lat") 
          let long = arrayForLocations.object(forKey: "lng") 
          let position = CLLocationCoordinate2D(latitude: lat as! CLLocationDegrees, longitude: long as! CLLocationDegrees) 

          let arrayForName = (arrayPlaces[i] as! NSDictionary).object(forKey: "name") as! String 
          let arrayForAddress = (arrayPlaces[i] as! NSDictionary).object(forKey: "vicinity") as! String 

          if let arrayForRating = (arrayPlaces[i] as! NSDictionary).object(forKey: "rating") as? NSNumber { 
           arrayOfRating.append(Double(truncating: arrayForRating).rounded(toPlaces: 1)) 
           self.eachCarouselDataDic[i] += [arrayForName, arrayForRating] 
           print(self.eachCarouselDataDic) 
          } else { 
           arrayOfRating.append(0.0) 
           self.eachCarouselDataDic[i] += [arrayForName,0.0] 
           print(self.eachCarouselDataDic) 
          } 
          print("-----------------------------------------------------------------------------------------------------") 

          print(self.eachCarouselDataDic.count) 

          print("-----------------------------------------------------------------------------------------------------") 
          arrayOfNames.append(arrayForName) 
          arrayOfAddress.append(arrayForAddress) 

          arrayOfLocations.append(position) 

          //self.eachCarouselDataDic[i] += [arrayForName,arrayForRating] 

          //self.drawPolylineAmongMultiplePoints(coordinate: position, index: counter) 
          counter += 1 
          let nearbyMarker = GMSMarker() 
          //var position = CLLocationCoordinate2D() 
          nearbyMarker.iconView = markerView 

          name = arrayOfNames[i] 
          nearbyMarker.tracksViewChanges = true 
          nearbyMarker.title = name 

          nearbyMarker.position = position 
          nearbyMarker.snippet = "Rating = \(arrayOfRating[i]) \(self.ratingSystem(rating: arrayOfRating[i]))\n Address = \(arrayOfAddress[i])" 

          nearbyMarker.map = self.mapView 
         } 


        } 

        for i in 0..<counter { 
         self.drawPolylineAmongMultiplePoints(coordinate: arrayOfLocations[i], pinPoint: i) 
        } 


       } 



      }catch let error as NSError { 
       print(error.debugDescription) 
      } 



     default: 
      print("HTTP Reponse Code: \(httpResponse.statusCode)") 

     } 

    } 
    task.resume() 




    UIView.animate(withDuration: 3, animations: { 
     self.isCarouselActive = true 
     self.myLocationButton.setImage(UIImage(named: "carousel"), for: .normal) 
    }) 
} 
+1

Dies ist schwer zu lesen. Können Sie die Frage bearbeiten und formatieren, damit sie leichter zu lesen ist? – Goose

Antwort

0

Der Fehler sagt Ihnen, das Problem:

index 0 beyond bounds for empty NSArray 

So haben Sie ein leeres Array, wenn Sie nicht erwarten Sie.

Verwenden Sie den Debugger und/oder print() Anweisungen, um die Werte Ihrer Variablen zu untersuchen. Arbeite von dem Punkt des Scheiterns zurück, um herauszufinden, wo es schief geht.

Sie müssen das wirklich selbst tun, Sie haben eine Menge Code zur Verfügung gestellt, damit die Leute durcharbeiten können. Wenn Sie nicht weiterkommen und das Problem nicht lösen können, müssen Sie eine neue Frage stellen, nur genügend Code einreichen, um das Problem zu zeigen, erklären, was Sie getan haben und nicht herausfinden können usw. Jemand wird Ihnen zu diesem Zeitpunkt zweifellos helfen.

Verwandte Themen