Show Current User Location with MKMapView?

白昼怎懂夜的黑 提交于 2019-12-20 15:25:12

问题


I am trying to show current location of user by setting the property of MKMapView i.e setShowsUserLocation to YES. As by default an arrow appears on the top left of iPhone screen when the application starts updating the user location.But after showing the current location the arrow should disappear but its still present as long as the app is running which would mean the app is still updating the location in the background? so how can i stop updating the current location? i have implemented the delegate which gets called up immediately..


回答1:


If the map is visible and has showUserLocation set to YES, it continues to update in the background.

You need to unset this when the view disappears or when the Application goes to background. The best way would probably be to register your viewController to be notified for UIApplicationDidEnterBackgroundNotification and UIApplicationDidBecomeActiveNotification.

- (void)viewDidLoad{
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appToBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appReturnsActive) name:UIApplicationDidBecomeActiveNotification object:nil];
} 

Then in the method called by this notification, change the map view properties regarding userLocation:

- (void)appToBackground{
  [mapview setShowsUserLocation:NO];
}

And

- (void)appReturnsActive{
  [mapview setShowsUserLocation:YES];
}

Check that these methods are indeed called by setting a breakpoint there and returning to the home screen.




回答2:


I agree with Michael Kernahan, I'm pretty sure there is a race condition inside MKMapView.

MKMapView appears to try to remove the userLocationAnnotation (the blue dot) by itself as soon as it realises it lost access to location services.

However, that does not seems protected and if the developer also issues a [mapView setShowsUserLocation:NO], it is very likely to get a crash because of the race between MKMapView's internal thread trying to remove the userLocationAnnotation, and the thread that is calling setShowsUserLocation:NO.




回答3:


You can stop updating the location by sending a message to the location's manager [self.locationManager stopUpdatingLocation];

As for your case, did you try to stop showing the users location?



来源:https://stackoverflow.com/questions/9924653/show-current-user-location-with-mkmapview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!