В чем причина вылета программы при построении маршрута от точки А к Б?

Использую google maps в ios приложении, в котором строится маршрут от текущего местоположения до сохраненной позиции с помощью google maps directions API.
Код построения маршрута:
-(void) getRoadTo {
    rectangle.map = nil;
//    NSString *str= [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true&mode=walking&KEY=AIzaSyDCLfvIDIxLALbEOFufd_lZzn_rJbpAXqg", userLocation.coordinate.latitude, userLocation.coordinate.longitude, [Singleton sharedSingleton].location.coordinate.latitude, [Singleton sharedSingleton].location.coordinate.longitude];
    
    NSString *str= [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true&mode=walking&KEY=AIzaSyDCLfvIDIxLALbEOFufd_lZzn_rJbpAXqg", userLocation.coordinate.latitude, userLocation.coordinate.longitude, 55.50998, 37.1337];
    
    NSURL *url=[[NSURL alloc]initWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSArray *latestRoutes = [json objectForKey:@"routes"];
    NSString *points=[[[latestRoutes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
    
    
    //--Вариант 2--//
    rectangle = [GMSPolyline polylineWithPath: [GMSPath pathFromEncodedPath: points]];
    rectangle.map = mapView;
    rectangle.strokeColor = [UIColor colorWithRed:99./256. green:174./256. blue:197./256. alpha:1.];
    rectangle.strokeWidth = 5.0;
    
    //--Вариант 1--//
    
//    @try {
//        NSArray *temp= [self decodePolyLine:[points mutableCopy]];
//        GMSMutablePath *path = [GMSMutablePath path];
//    
//        for(int idx = 0; idx < [temp count]; idx++){
//            CLLocation *location = [temp objectAtIndex:idx];
//            [path addCoordinate:location.coordinate];
//        }
//        
//        
//
//        
//
//        rectangle = [GMSPolyline polylineWithPath:path];
//        rectangle.strokeWidth = 5.0;
//        rectangle.map = mapView;
//        rectangle.strokeColor = [UIColor colorWithRed:99./256. green:174./256. blue:197./256. alpha:1.];
//    }
//    @catch (NSException * e) {
//    }
}

Метод декодирования для первого варианта:
-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
    [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
                                options:NSLiteralSearch
                                  range:NSMakeRange(0, [encoded length])];
    NSInteger len = [encoded length];
    NSInteger index = 0;
    NSMutableArray *array = [[NSMutableArray alloc] init] ;
    NSInteger lat=0;
    NSInteger lng=0;
    while (index < len) {
        NSInteger b;
        NSInteger shift = 0;
        NSInteger result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5] ;
        NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5] ;
        CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] ;
        [array addObject:loc];
    }
    
    return array;
}

Все бы ничего, если бы при большом расстоянии от точки А до Б программа не вылетала бы с ошибкой:
994b448899564a03b8bc6b0ad222376f.png
В чем причина ума не приложу..
  • Вопрос задан
  • 279 просмотров
Пригласить эксперта
Ответы на вопрос 1
alexyat
@alexyat
iOS Developer
там же написано в чем причина, обращение в пустой массив к элементу 0
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы