[["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
一直在弹出......
任何人都有好主意解决这个问题?
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)
})
}
答案 0 :(得分:-1)
错误告诉您问题:
index 0 beyond bounds for empty NSArray
所以当你不期望一个时,你有一个空数组。
使用调试器和/或print()
语句检查变量的值。从失败的角度回过头来发现它出错的地方。
你真的需要自己做,你已经为人们提供了很多代码。如果你遇到困难并且无法解决问题所有的新问题,请包含足够的代码以显示问题,解释你已经完成的事情并且无法弄清楚等等。当然,有人会帮助你。