【发布时间】:2018-06-10 12:52:26
【问题描述】:
我有一个 UIViewController,我想在其中显示以当前位置为中心的地图。
AppDelegate 的 didFinishLaunchingWithOptions 方法如下所示:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.locationManager = [[CLLocationManager alloc] init];
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
return YES;
}
我的 UIViewController.m 类如下所示:
@interface GMapViewController ()<CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (strong, nonatomic) CLLocation *currentLocation;
@end
@implementation GMapViewController
#pragma mark - Lifecycle methods
- (void)viewDidLoad {
[super viewDidLoad];
self.currentLocation = [CLLocation new];
[[[AppDelegate appDelegate] locationManager] setDelegate:self];
MKCoordinateRegion visibleRegion;
visibleRegion.center = self.currentLocation.coordinate;
visibleRegion.span = MKCoordinateSpanMake(200, 200);
[self.mapView setRegion:visibleRegion animated:YES];
}
#pragma mark - CLLocationManagerDelegate's methods
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
self.currentLocation = [locations lastObject];
}
问题是 CLLocationManager 的 didUpdateLocations 委托方法调用太晚,因为调用 viewDidLoad 时 currentLocation 属性没有值。
如何在调用 viewDidLoad 之前获取当前坐标?
【问题讨论】:
-
为什么不直接在视图控制器中导入 CoreLocation?
-
CoreLocation 已导入 AppDelegate
-
GMapViewController中的viewDidLoad很可能比AppDelegate中的didFinishLaunchingWithOptions更早被调用。懒惰地初始化locationManager,设置委托后将startUpdatingLocation移动到viewDidLoad。 -
@vadian,didFinishLaunchingWithOptions 的调用早于 viewDidLoad
-
“如何在调用 viewDidLoad 之前获取当前坐标” - 你不能也不应该尝试。调用
didUpdateLocations时更新地图的区域。在发生之前展示一些合理的东西。
标签: ios objective-c cllocationmanager cllocation