ios - 使用 MKMapView 获取用户当前坐标( objective-c ,xcode 6)

标签 ios mkmapview cllocationmanager

我的代码如下:

#import "radSecondViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface radSecondViewController ()

@end

CLLocationManager *locationManager = nil;

@implementation radSecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];

}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *newLocation = [locations lastObject];
    CLLocation *oldLocation;
    if (locations.count > 1) {
        oldLocation = [locations objectAtIndex:locations.count-2];
    } else {
        oldLocation = nil;
    }
    NSLog(@"didUpdateToLocation %@ from %@", newLocation, oldLocation);
    MKCoordinateRegion userLocation = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 1500.0, 1500.0);
}
//snipped memory dump
@end

如您所见,每次发生坐标变化时,我都会尝试让控制台记录坐标变化。

然而,当我构建应用程序时,没有任何内容输出到控制台。当我将断点添加到 locationManager:updateLocation... 行时,它们永远不会被命中。

我已经在模拟器中将位置设置到几个地方(苹果、高速公路等)。

有没有人遇到过类似的问题并找到了解决方法?或者这是我犯的新手错误?我是 Xcode 和 Objective C 的新手。

感谢您的帮助!

最佳答案

您尚未设置位置管理器的 delegate 属性。

locationManager.delegate = self;

并将您的类扩展更新为:

@interface radSecondViewController () <CLLocationManagerDelegate>

@end

并更改行:

CLLocationManager *locationManager = nil;

位于@imlpementation block 内:

@implementation radSecondViewController {
    CLLocationManager *locationManager = nil;
}

如您所见,它被声明为全局变量而不是实例变量。

关于ios - 使用 MKMapView 获取用户当前坐标( objective-c ,xcode 6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826251/

相关文章:

ios - 自定义注释的属性在委托(delegate)方法中不可见

iOS 13 在应用程序被终止时跟踪用户位置

ios - CLLocation distanceFromLocation大值

ios - Instagram 相机页面

ios - Firebase 数据库结构 - 需要建议

ios - 添加注释时 MKMapView 崩溃

iphone - 在 Overlays 可见时隐藏 MKMapView

iphone - UIImagePickerController 不会停止定位服务

android - 在 IOS 上从 Flutter 启动 Whatsapp 时出现问题

iphone - 将数据插入 SQLite db iPhone 的正确方法