-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' 

から出る維持されます上記の場所名、評価、場所(CLLocationCoordinate2D)をダブル・アレイに保存し、インデックスと場所をdrawPolylineAmongMultiplePointsに解析して、距離と継続時間を見つけ、ダブル・アレイに追加またはプッシュします。 NSRangeExceptionはポップアップ状態を維持しています。'NSRangeException'、理由:[__NSArray0 objectAtIndex:]:空のNSArrayのための境界を越えてインデックス0 - 私が得れば>それは、インデックスの境界

これを解決するには誰でも良いアイデアがありますか?

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

これは読みにくいです。質問を編集して読みやすいように書式を設定できますか? – Goose

答えて

0

エラーはあなたの問題を伝えます:

index 0 beyond bounds for empty NSArray 

あなたがものを期待していないとき、あなたは空の配列を持っています。

デバッガまたはprint()ステートメントを使用して、変数の値を調べます。失敗の地点から戻って、どこが間違っているかを発見してください。

あなたは本当にこれを行う必要があります。人々が作業するための多くのコードを用意しています。あなたが立ち往生し、問題をすべて明らかにすることができない場合は、問題を示す十分なコードを入れ、あなたがしたことを説明し、理解できないなど、間違いなくあなたを助けるでしょう。

関連する問題