Ios 用户位置Mapkit ViewDidLoad

Ios 用户位置Mapkit ViewDidLoad,ios,mapkit,mkuserlocation,Ios,Mapkit,Mkuserlocation,因此,从我在这里看到的多个答案来看,这是如何在应用程序加载时集中和缩放用户位置,并且效果很好 -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ NSLog(@"Did update user location"); MKCoordinateRegion mapRegion; mapRegion.center = mapView.userLoca

因此,从我在这里看到的多个答案来看,这是如何在应用程序加载时集中和缩放用户位置,并且效果很好

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    NSLog(@"Did update user location");
    MKCoordinateRegion mapRegion;
    mapRegion.center = mapView.userLocation.coordinate;
    mapRegion.span.latitudeDelta = 0.2;
    mapRegion.span.longitudeDelta = 0.2;

    [map setRegion:mapRegion animated: YES];

}
但每次调用此委托方法时,当您开始使用映射时,它会将我带回用户位置。我应该停止用户位置更新吗?我试着把这段代码放在视图中,加载只是为了得到初始的缩放和居中,但它不起作用?或者我可以把代码放在另一个MapKit委托方法中,我只是不知道该用哪个方法。其他人是怎么做到的

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
是每次更改用户位置时调用的mapKit委托方法。这就是为什么每次通话时,地图都会以用户的位置为中心。当应用程序启动时,你不能用它来初始化用户位置上的地图

我认为如果它在viewDidLoad上不起作用,那是因为当时应用程序还不知道用户的位置。在那里放一个断点,自己看看

对我来说,你应该在viewDidLoad中添加一个观察者,当应用程序获取用户位置的数据时调用它

// Check if user authorized use of location services
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) {
    // Add observer
    [self.mapView.userLocation addObserver:self
                                forKeyPath:@"location"
                                   options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
                                   context:NULL];
}
然后在

- (void)observeValueForKeyPath:(NSString *)keyPath
                  ofObject:(id)object
                    change:(NSDictionary *)change
                   context:(void *)context;
等待调用keyPath“location”。 当它第一次触发时,视图被加载,应用程序知道用户的位置。然后,您可以将代码放在用户位置的地图中心。 但是,请确保移除观察者,这样它不会多次收到呼叫

[self.mapView.userLocation removeObserver:self
                                   forKeyPath:@"location" context:NULL];

妙极了!你完全正确,用户位置还没有找到!谢谢