我正在使用 CoreLocation 并从我的应用程序 AppDelegate 中启动 locationManager。下面的示例代码...
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...
// start location manager
if([CLLocationManager locationServicesEnabled])
{
myLocationManager_ = [[CLLocationManager alloc] init];
myLocationManager_.delegate = self;
[myLocationManager_ startUpdatingLocation];
}
else
{
// ... rest of code snipped to keep this short
在这个方法中我们可以看到更新后的位置。
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSString *currentLatitude = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.latitude];
NSLog(@"AppDelegate says: latitude: %@", currentLatitude);
// ... rest of code snipped
现在,在我的应用程序的其他区域中,我需要确定用户当前位置(纬度、经度)。我可以将上面的代码合并到需要当前位置的 ViewController 中,但随后我会运行多个 CLLocationManager 实例(我认为) - 为什么要重复此代码?有没有一种方法可以让我从其他 ViewController 中获取 AppDelegate 的位置信息?
PS - 我正在使用带有 ARC 的 Xcode 4.3
最佳答案
谢谢莫哈比塔为我回答这个问题!为了清楚起见,我发布了我的代码供其他人欣赏。
注意:下面仅显示相关部分。
AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) CLLocationManager *myLocationManager;
@property (nonatomic, strong) CLLocation *currentLocation;
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
if([CLLocationManager locationServicesEnabled])
{
currentLocation_ = [[CLLocation alloc] init];
myLocationManager_ = [[CLLocationManager alloc] init];
myLocationManager_.delegate = self;
[myLocationManager_ startUpdatingLocation];
}
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
currentLocation_ = newLocation;
}
其他ViewControllers.h
@property (strong, nonatomic) CLLocation *currentLocation;
其他ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
if([CLLocationManager locationServicesEnabled])
{
AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
currentLocation_ = [[CLLocation alloc] initWithLatitude:appDelegate.currentLocation.coordinate.latitude longitude:appDelegate.currentLocation.coordinate.longitude];
}
}
再次感谢!
关于iphone - 从其他 ViewController 的 locationManager 方法访问 newLocation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638279/