【发布时间】:2014-11-13 00:58:17
【问题描述】:
我正在尝试在我的 iOS 项目中使用 CLLocationManager 框架来访问用户的位置,但是当我调用时
[locationManager startUpdatingLocation]
locationManager:didUpdateLocations: 或 locationManager:didFailWithError: 都没有被调用。
//myViewController.h
@interface myViewController : UITableViewController <CLLocationManagerDelegate>
@end
//myViewController.m
@implementation myViewController{
CLLocationManager *locationManager;
}
//edit
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
}
//finish edit
-(void)getLocation
{
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error"
message:@"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *newLocation = locations[[locations count] -1];
CLLocation *currentLocation = newLocation;
NSString *longitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
NSString *latitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
if (currentLocation != nil) {
NSLog(@"latitude: %@", latitude);
NSLog(@"longitude: @"%@", longitude);
}else {
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[errorAlert show];
}
}
@end
尽管文档中说了什么,但都没有调用委托方法:
“此方法立即返回。调用此方法会导致位置管理器获取初始位置修复(可能需要几秒钟)并通过调用其 locationManager:didUpdateLocations: 方法通知您的委托 [...] 除了您的委托对象实现了locationManager:didUpdateLocations: 方法,它也应该实现locationManager:didFailWithError: 方法来响应潜在的错误。”
不知道如何调试问题。
谢谢,
JA
【问题讨论】:
-
getLocation被调用了吗?您是否在寻找locationServicesEnabled退货或authorizationStatus退货? -
是的,
get location被调用。不完全确定locationServicesEnabled是什么意思。locationManager:didChangeAuthorizationStatus应该返回什么? -
您是否初始化了位置管理器。 [[CLLocationManager alloc] 初始化]
-
是的,
viewDidLoad对不起,我忘了包括那个 -
你在用模拟器吗?如果是这样,这在 StackOverflow 上被问了太多次了
标签: ios objective-c cllocationmanager