【发布时间】:2023-04-09 09:57:01
【问题描述】:
我正在使用核心位置框架来定位设备,并且一旦使用位置调用 locationManager:didUpdateToLocation:fromLocation: 方法,我就会停止跟踪用户。
但是,当我第一次启动应用程序时(从全新安装)。当我向我的位置管理器发送 startUpdatingLocation 消息时,用户会收到接受或拒绝位置服务的警报。
当我接受不开始跟踪时,只有当我离开并返回此视图控制器时,当再次调用 startUpdatingLocation 时才会开始通知。
我正在实现 locationManager:didChangeAuthorizationStatus: 认为当用户接受(或拒绝)位置服务时会收到消息,但事实并非如此。
一旦位置服务消息被解除,谁能指出我更新位置的正确方向?
谢谢。
使用代码示例更新
我有一个封装我的逻辑的单例类,其想法是当请求用户位置时,会检查 CLLocation 的时间戳,如果它太旧,则会向开始跟踪发送消息,这会延迟加载我的 CLLocationManager iVar ,
-(void)startTracking{
if(!self.locationManager)
_locationManager = [[CLLocationManager alloc] init];
if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
[self invalidateUserLocation];
}else{
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
}
收到新位置:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
_userLocation = [newLocation retain];
NSDictionary * info = [NSDictionary dictionaryWithObject:self.userLocation
forKey:@"userLocation"];
[[NSNotificationCenter defaultCenter] postNotificationName:kUserLocationFound
object:self
userInfo:info];
[self stopTracking];
}
停止跟踪:
-(void)stopTracking{
if(!self.locationManager)
return;
[self.locationManager stopUpdatingLocation];
self.locationManager.delegate = nil;
}
当我有一个需要用户位置的视图控制器时,我会像这样在我的单例对象上调用 userLocation。如果它是最近的,我返回 CLLocation,否则我返回 nil 并重新开始。请注意,当我收到第一次更新时,我会停止跟踪。但是第一次运行并且我得到警报视图时,根本没有跟踪任何内容。
- (CLLocation*)userLocation
{
if(_userLocation.coordinate.latitude == 0 && _userLocation.coordinate.longitude == 0){
[self startTracking];
return nil;
}else{
NSDate* timeNow = [NSDate date];
NSTimeInterval interval = [timeNow timeIntervalSinceDate:_userLocation.timestamp];
if(interval >10)
[self startTracking];
return _userLocation;
}
}
【问题讨论】:
-
您是否在您的 CLLocationManager 实例上调用 startUpdatingLocation?
-
没错,我在我的 CLLocationManager 实例上调用它。
-
请给我一些代码好吗?
标签: ios core-location