我正在创建一个使用核心位置的应用,这是我的代码:
.h:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface ViewController : UIViewController
<CLLocationManagerDelegate>
@property(strong,nonatomic) CLLocationManager *manager;
@end
.m:
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()
@end
@implementation ViewController
@synthesize manager;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad
{
[super viewDidLoad];
if (!self.manager)
{
self.manager=[CLLocationManager new];
}
self.manager.delegate = self;
self.manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
[self.manager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation * currentLocation = (CLLocation *)[locations lastObject];
NSLog(@"Location: %@", currentLocation);
if (currentLocation != nil)
{
NSLog([NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]);
NSLog([NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]);
}
}
@end
问题是未调用
didUpdateToLocation
。我尝试在其中放置一个断点,但没有任何反应。
最佳答案
为了使iOS位置跟踪正常运行,这是前提条件,并且顺序也很重要:
将您的班级定义为CLLocationManagerDelegate
。
实例化CLLocationManager
实例。
将其delegate
设置为self
。
设置其各种属性(准确性等)
如果需要,请致电[CLLocationManagerDelegate startUpdatingLocation]
。
监听委托方法didUpdateLocations
中的位置更新,该方法在指定为CLLocationManagerDelegate
的类中实现。
使用您的代码,以下是您需要更正的事项:
-(IBAction)submit
{
[self.manager startUpdatingLocation];
}
- (void)viewDidLoad
{
[super viewDidLoad];
if (!self.manager)
{
self.manager=[CLLocationManager new];
}
self.manager.delegate = self;
self.manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
}
简而言之,在告诉它开始更新位置之前,您需要实例化它并正确设置其属性。当前,您正在执行相反的操作。
更新
同样,从iOS 6开始不赞成使用委托方法
didUpdateToLocation
。您必须将其替换为newer method,如下所示:- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation * currentLocation = (CLLocation *)[locations lastObject];
NSLog(@"Location: %@", currentLocation);
if (currentLocation != nil)
{
self.latitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
self.longitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
}
}
关于ios - iOS CLLocationManagerDelegate didUpdateToLocation没有被调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24961757/