2017-03-08 77 views
1

叫我面對此錯誤,而拉伸折線通過使用谷歌API終止應用程序由於未捕獲的異常GMSThreadExceptionGMSThreadException」原因:‘的API的方法必須從主線程’

-(void)drawRoute 

{

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL); 
dispatch_async(myQueue, ^{ 

    [self fetchPolylineWithOrigin:origin destination:destination completionHandler:^(GMSPolyline *polyline) 
    { 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      // Update the UI 
      if(polyline) 
       polyline.map = mapView; 
      [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
     }); 

    }]; 

}); 

}

回答

1

在主線程上使用GMSPath和GMSPolyline以及它應該工作。

0

從你的錯誤信息,看來你只能調用從主線程API方法,請嘗試使用:

-(void)drawRoute 
{ 

dispatch_async(dispatch_get_main_queue(), ^{ 

    [self fetchPolylineWithOrigin:origin destination:destination completionHandler:^(GMSPolyline *polyline) 
    { 
     // Update the UI 
     if(polyline) 
      polyline.map = mapView; 
     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    }]; 

}); 
} 

這將仍然允許您的代碼在它消失時繼續執行,因爲它是異步的,但將它保留在主線程(隊列)上。該方法有一個完成處理程序的事實表明它本身是異步的,也許你根本不需要在這裏進行調度?

我的選擇將是你會被罰款的事:

-(void)drawRoute 
{ 

    [self fetchPolylineWithOrigin:origin destination:destination completionHandler:^(GMSPolyline *polyline) 
    { 
     // Update the UI 
     if(polyline) 
      polyline.map = mapView; 
     [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    }]; 

} 

或有您以前遇到性能問題呢?

0

對我來說,它的苛刻使用主線程在兩個地方

一個是...

__block GMSMapView *mapView; 
dispatch_async(dispatch_get_main_queue(), ^{ 
    // Create GMSMapView 
    mapView = [GMSMapView mapWithFrame:CGRectMake(1, 1, _subView.frame.size.width-2, _subView.frame.size.height-2) camera:camera]; 
    mapView.myLocationEnabled = YES; 
    [_subView addSubview:mapView]; 
}); 

第二個是...

- (void)fetchPolylineWithOrigin:(CLLocation *)origin destination:(CLLocation *)destination completionHandler:(void (^)(GMSPolyline *))completionHandler { 

    // Code here .... 

    __block GMSPolyline *polyline = nil; 
    dispatch_async(dispatch_get_main_queue(), ^{ // Second main 
     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]; 
     } 
    }); 
} 
相關問題