Bra*_*don 5 iphone xcode core-location locationmanager ios
我想在viewController出现时获取用户的坐标.我需要几个viewControllers中的位置,所以我将locationManager放在appDelegate中.我的问题是,在第一个viewDidAppear上,尚未找到坐标.我该怎么做才能改变这个?谢谢你们!!!
我的AppDelegate有这个:
- (NSString *)getUserCoordinates
{
NSString *userCoordinates = [NSString stringWithFormat:@"latitude: %f longitude: %f",
locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
return userCoordinates;
}
Run Code Online (Sandbox Code Playgroud)
我的viewController获取坐标:
- (void)viewDidAppear
{
NSString *userCoordinates =[(PDCAppDelegate *)[UIApplication sharedApplication].delegate
getUserCoordinates];
}
Run Code Online (Sandbox Code Playgroud)
我最近在AppDelegate中实现了同样的东西,位置管理器,以便我的ViewControllers都可以访问位置数据.
不要忘记实现CoreLocation委托方法,特别是didUpdateLocations以获取新的位置数据.我会把它放在AppDelegate类中.
因为,你有一个关系,一个对象(AppDelegate)需要通知许多viewControllers有关位置更新,我建议使用NSNotification.
在你的AppDelegate中,你会写...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// set up location manager
self.locationManager = [[CLLocationManager alloc] init];
[self.locationManager setDelegate:self];
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager startUpdatingLocation];
return YES;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
CLLocation * newLocation = [locations lastObject];
// post notification that a new location has been found
[[NSNotificationCenter defaultCenter] postNotificationName:@"newLocationNotif"
object:self
userInfo:[NSDictionary dictionaryWithObject:newLocation
forKey:@"newLocationResult"]];
}
Run Code Online (Sandbox Code Playgroud)
在ViewController中,您不会使用viewDidAppear方法.相反,你会这样做......
- (void)viewDidLoad
{
[super viewDidLoad];
// subscribe to location updates
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updatedLocation:)
name:@"newLocationNotif"
object:nil];
}
Run Code Online (Sandbox Code Playgroud)
你会有一个看起来像这样的方法updatedLocation
-(void) updatedLocation:(NSNotification*)notif {
CLLocation* userLocation = (CLLocation*)[[notif userInfo] valueForKey:@"newLocationResult"];
}
Run Code Online (Sandbox Code Playgroud)
您可以让其他viewControllers通过将它们添加为观察者来订阅通知更新.
| 归档时间: |
|
| 查看次数: |
3773 次 |
| 最近记录: |