Сбой на polylineWithPath: путь GMSThreadException

Я использую этот исходный код для рисования маршрута, но получаю сбой на линии,

 polyline = [GMSPolyline polylineWithPath:path];

Завершение работы приложения из-за необработанного исключения "GMSThreadException", причина: "Все вызовы Google Maps SDK для iOS должны выполняться из потока пользовательского интерфейса".

Даже я прошел, но не работает для меня.

2 ответа

При выполнении обновлений пользовательского интерфейса в замыканиях, не забудьте get main thread and perform UI Operations только в основной ветке.

Ошибка, которую я сделал, я пытаюсь построить маркеры в блоке завершения веб-сервиса.

dispatch_async(dispatch_get_main_queue(),
{
    //Your code...
})

Вызовите свой метод в основном потоке.

Цель-C

dispatch_async(dispatch_get_main_queue(), ^{
    [self callMethod];
});

Swift 3 вперед

DispatchQueue.main.async {
    self.callMethod()
}

Ранее Swift

dispatch_async(dispatch_get_main_queue()) {
    self.callMethod()
}
//Drawing Route Between Two Places on GMSMapView in iOS
- (void)drawRoute
{
CLLocation *myOrigin = [[CLLocation alloc]initWithLatitude:latitudeValue longitude:longitudeValue];
CLLocation *myDestination = [[CLLocation alloc] initWithLatitude:30.7333 longitude:76.7794];
[self fetchPolylineWithOrigin:myOrigin destination:myDestination completionHandler:^(GMSPolyline *polyline)
 {
     if(polyline)
         polyline.map = myMapView;
 }];
}

- (void)fetchPolylineWithOrigin:(CLLocation *)origin destination:(CLLocation *)destination completionHandler:(void (^)(GMSPolyline *))completionHandler{
    NSString *originString = [NSString stringWithFormat:@"%f,%f", origin.coordinate.latitude, origin.coordinate.longitude];
    NSString *destinationString = [NSString stringWithFormat:@"%f,%f", destination.coordinate.latitude, destination.coordinate.longitude];
    NSString *directionsAPI = @"https://maps.googleapis.com/maps/api/directions/json?";
    NSString *directionsUrlString = [NSString stringWithFormat:@"%@&origin=%@&destination=%@&mode=driving", directionsAPI, originString, destinationString];
    NSURL *directionsUrl = [NSURL URLWithString:directionsUrlString];
    NSURLSessionDataTask *fetchDirectionsTask = [[NSURLSession sharedSession] dataTaskWithURL:directionsUrl completionHandler:
                                                 ^(NSData *data, NSURLResponse *response, NSError *error)
                                                 {
                                                     NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
                                                     if(error)
                                                     {
                                                         if(completionHandler)
                                                             completionHandler(nil);
                                                         return;
                                                     }
                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                         //Your code...
                                                         NSArray *routesArray = [json objectForKey:@"routes"];
                                                         GMSPolyline *polyline = nil;
                                                         if ([routesArray count] > 0)
                                                         {
                                                             NSDictionary *routeDict = [routesArray objectAtIndex:0];
                                                             NSDictionary *routeOverviewPolyline = [routeDict objectForKey:@"overview_polyline"];
                                                             NSString *points = [routeOverviewPolyline objectForKey:@"points"];
                                                             GMSPath *path = [GMSPath pathFromEncodedPath:points];
                                                             polyline = [GMSPolyline polylineWithPath:path];
                                                             polyline.strokeWidth = 3.f;
                                                             polyline.strokeColor = [UIColor blueColor];
                                                             polyline.map = myGoogleMapView;
                                                             self.customMapViewRef = myGoogleMapView;
                                                         }
                                                     });
                                                 }];
    [fetchDirectionsTask resume];
}
Другие вопросы по тегам