在应用的多个部分中调用位置 [英] Calling Location in Multiple Parts of App

查看:81
本文介绍了在应用的多个部分中调用位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用以下代码在我的应用的多个部分中找到用户的位置。为避免复杂性,我只想在一个位置获得用户的位置。我假设我需要将其放入我的appDelegate中,然后在需要使用它时从其他视图中以某种方式调用它。除了我的appDelegate之外,有人知道我需要使用什么来将位置作为NSString放在视图/选项卡上吗?谢谢!

I want to use the following code to find a user's location in multiple parts of my app. To avoid complexity, I only want to have one place where I get the user's location. I would assume that I need to put it in my appDelegate and then call it somehow from the other views when I need to use it. Does anyone know what I would need to use to get the location as an NSString on the views/tabs other than my appDelegate? Thank you!

- (NSString *)deviceLocation {
NSString *theLocation = [NSString stringWithFormat:@"latitude: %f longitude: %f", 
locationManager.location.coordinate.latitude, 
locationManager.location.coordinate.longitude];
return theLocation;
}

- (void)viewDidLoad
{
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}


推荐答案

移动所有位置侦听器以及与应用程序委托相关的内容,然后使 NSString * location 属性 AppDelegate 中的a>,现在每当您获得更新位置时,将其设置为其他<$中的 NSString * location c $ c> ViewControllers ,在需要时访问应用程序委托的location属性。

Move all of your location listener and related stuff to the app delegate, and then make NSString *location property of AppDelegate, now whenever you get an updated location set that to NSString *location, in your other ViewControllers, when you need, access the app delegate's location property.

如果您确实需要更新的位置,则可以使用 NSNotificationCenter 并广播有关新位置更新的通知,因此确实需要更新位置的 ViewController 会为有关新位置的通知进行注册并相应地进行操作。

If you really need an updated location you can use NSNotificationCenter and broadcast a notification about new location update, so the ViewController which really need an updated location will register itself for Notification about new location and will do stuff accordingly.

这篇关于在应用的多个部分中调用位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆