我正在创建一个使用核心位置的应用,这是我的代码:
.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
没有被调用。
我尝试在其中放置一个断点,没有任何反应。
答案 0 :(得分:1)
要使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];
}
}
答案 1 :(得分:0)
您需要将这些密钥添加到Info.plist中:
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
如果iOS8:
还请求您要授权的类型if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
{
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
因此,系统将显示警告&#34;允许&#34; app&#34;访问你的位置......?允许将启动您的位置管理员并将调用didUpdateLocations
。