我试图获取用户当前位置的经度/纬度,我的代码就是这样:
MyLocationManager.h
@interface MyLocationManager : NSObject
+(MyLocationManager*)sharedInstance;
-(void)checkAndStartLocationManager;
-(void)stopUpdatingLocation;
@end
MyLocationManager.m
+ (MyLocationManager*)sharedInstance
{
static id _sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[self alloc] init];
MyLocationManager *instance = _sharedInstance;
instance.locationManager = [CLLocationManager new];
instance.locationManager.delegate = instance;
instance.locationManager.distanceFilter = 100;
instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
instance.locationManager.pausesLocationUpdatesAutomatically = YES;
instance.locationManager.activityType = CLActivityTypeOtherNavigation;
});
return _sharedInstance;
}
-(void)checkAndStartLocationManager
{
switch([CLLocationManager authorizationStatus])
{
case kCLAuthorizationStatusAuthorizedWhenInUse:
[self startUpdatingLocation];
break;
case kCLAuthorizationStatusNotDetermined:
if ([self.locationManager respondsToSelector:
@selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
}
break;
case kCLAuthorizationStatusRestricted:
break;
case kCLAuthorizationStatusDenied:
break;
case kCLAuthorizationStatusAuthorizedAlways:
[self startUpdatingLocation];
break;
default:
break;
}
}
-(void)startUpdatingLocation
{
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch([CLLocationManager authorizationStatus])
{
case kCLAuthorizationStatusAuthorizedWhenInUse:
[self startUpdatingLocation];
break;
case kCLAuthorizationStatusNotDetermined:
break;
case kCLAuthorizationStatusRestricted:
break;
case kCLAuthorizationStatusDenied:
break;
case kCLAuthorizationStatusAuthorizedAlways:
[self startUpdatingLocation];
break;
default:
break;
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations: (NSArray *)locations
{
CLLocation *location = [locations lastObject];
NSString*locationInfo = [NSString stringWithFormat:@"lat - %f, lon - %f", location.coordinate.latitude, location.coordinate.longitude];
NSLog(@"Location is %@", locationInfo);
[self.locationManager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError: (NSError *)error
{
NSLog(@"didFailWithError: %@", error);
}
我正在使用ios 8并在iphone 5设备上进行测试。每当我打电话时,
[[MyLocationManager sharedInstance] checkAndStartLocationManager];
如果手机上的wifi打开,则只有
didUpdateLocations
正在被召唤。 如果 wifi关闭且只有 3G开启,则我始终收到错误,
错误Domain = kCLErrorDomain Code = 0“无法完成操作。(kCLErrorDomain错误0。)”
请帮助!!!
答案 0 :(得分:1)
设备使用WiFi通过众包热点快速确定位置,尽管结果可能不准确。禁用WiFi时,唯一剩下的可能是使用GPS模块。但是,如果你在某个建筑物或GPS信号不够强大,确定你的位置需要更多的时间,你会得到一段时间的消息