iphone – 从appDelegate中的locationManager传递坐标到viewCont
发布时间:2020-12-14 17:56:42 所属栏目:百科 来源:网络整理
导读:我想在viewController出现时获取用户的坐标.我需要几个viewControllers中的位置,所以我将locationManager放在appDelegate中.我的问题是,在第一个viewDidAppear上,尚未找到坐标.我该怎么做才能改变这个?谢谢你们!!! 我的AppDelegate有这个: - (NSString
我想在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; } 我的viewController获取坐标: - (void)viewDidAppear { NSString *userCoordinates =[(PDCAppDelegate *)[UIApplication sharedApplication].delegate getUserCoordinates]; } 解决方法
我最近在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"]]; } 在ViewController中,您不会使用viewDidAppear方法.相反,你会这样做…… - (void)viewDidLoad { [super viewDidLoad]; // subscribe to location updates [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatedLocation:) name:@"newLocationNotif" object:nil]; } 你会有一个看起来像这样的方法updatedLocation -(void) updatedLocation:(NSNotification*)notif { CLLocation* userLocation = (CLLocation*)[[notif userInfo] valueForKey:@"newLocationResult"]; } 您可以让其他viewControllers通过将它们添加为观察者来订阅通知更新. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |