我想使用以下代码在我的应用的多个部分中查找用户的位置。为了避免复杂性,我只想在一个地方找到用户的位置。我会假设我需要将它放在我的appDelegate中,然后在我需要使用它时从其他视图以某种方式调用它。有没有人知道我需要使用什么来获取除我的appDelegate之外的视图/选项卡上的NSString位置?谢谢!
- (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];
}
答案 0 :(得分:1)
将您的所有位置监听器和相关内容移至应用委托,然后在NSString *location
AppDelegate
NSString *location
时,只要您获得更新的位置设置为{{1}在您的其他ViewControllers
中,在您需要时,访问应用委托的位置属性。
如果您确实需要更新的位置,可以使用property并广播有关新位置更新的通知,因此真正需要更新位置的ViewController
会自行注册有关新位置的通知,并且做相应的事情。
答案 1 :(得分:1)
You can put your code in app delegate..like this
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
@public
float latitude;
float longituted;
}
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
if (locationManager==nil) {
locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[locationManager startUpdatingLocation];
}
if ([CLLocationManager regionMonitoringAvailable]) {//check service is available or not
[self startregionMonitoring];
}
[self.window makeKeyAndVisible];
return YES;
}
#pragma mark - GET Location
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation");
NSDate *eventData=newLocation.timestamp;
NSTimeInterval howRecent=[eventData timeIntervalSinceNow];
if (abs((howRecent)<15.0)) {
NSLog(@"latitude %+.6f, longitude %+.6f \n",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
CLLocationDistance dist=[newLocation distanceFromLocation:oldLocation]/1000;
NSLog(@"===================distance %5.1f traveled",dist);
latitude=newLocation.coordinate.latitude;
NSLog(@"lat :%+.5f",latitude);
longituted=newLocation.coordinate.longitude;
NSLog(@"long %+.6f",longituted);
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[locationManager stopUpdatingLocation];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[locationManager startUpdatingLocation];
}
now where you want latitude and longitude you can access [DELEGATE latitude];,[DELEGATE longitude]; where DELEGATE Is #define DELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]