【发布时间】:2015-03-12 08:17:04
【问题描述】:
我试图获取用户当前位置的经度/纬度,我的代码就是这样:
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 处于打开状态,那么我 总是收到错误,
Error Domain=kCLErrorDomain Code=0 "操作无法完成。(kCLErrorDomain error 0.)"
请帮忙!!!
【问题讨论】:
标签: ios objective-c iphone