如何在 AppDelegate 获取位置,并将纬度和经度传递给另一个 VC 并加载 webview

How to get location at AppDelegate, and pass the lat and long to another VC and load webview

已编辑

我已经通过使用 this 获得了当前位置。之后,我试图将经纬度作为字符串传递给另一个加载 webview 的方法。一个问题是每次我加载这个VC,它不会调用下面的方法

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 

然后直接跳转到下面的方法。

-(void)viewWillAppear:(BOOL)animated

如何首先获取位置并将其存储为变量,将它们作为字符串传递给另一个方法,附加一个字符串并将其传递给 NSURL 并加载 webview?

经纬度是否保留?我如何在整个项目中保留它?

当我点击其他选项卡控制器并再次点击这个 VC 时会发生什么。纬度和经度是否再次刷新?

- (void)viewDidLoad
{
    [super viewDidLoad];

    geocoder = [[CLGeocoder alloc] init];
    if (locationManager == nil)
    {
        locationManager = [[CLLocationManager alloc] init];
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        locationManager.delegate = self;
        [locationManager requestAlwaysAuthorization];
    }

    [locationManager startUpdatingLocation];

    dtDate = [[NSMutableArray alloc] init];
    self.currentPageIndex = 0;
    self.hasAppearedFlag = NO;

}

//=== It doesn't call a following method first. 
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *newLocation = [locations lastObject];

    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {

        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];
            latitude = [NSString stringWithFormat:@"%f",newLocation.coordinate.latitude];
            longitude = [NSString stringWithFormat:@"%f",newLocation.coordinate.longitude];
            state = placemark.administrativeArea;
            country = placemark.country;

            NSLog(@"This is the latitude%@", latitude);
            NSLog(@"This is the longitude%@", longitude);

        } else {
            NSLog(@"This is the error debug%@", error.debugDescription);
        }
    }];

    // Turn off the location manager to save power.
    [manager stopUpdatingLocation];

        //*** It will start loading this part below
        [self setupSegmentButtons];
        NSDate *now = [NSDate date];
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd/MM/YYYY"];
        NSString *dateString = [dateFormatter stringFromDate:now];

        [self LoadClasses:dateString];
        self.hasAppearedFlag = YES;
}

- (void)locationManager:(CLLocationManager *)manager
   didFailWithError:(NSError *)error
{
    NSLog(@"Cannot find the location.");
}

//=== Load webview

- (void)LoadClasses : (NSString *)sDate{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    sMemCode = [defaults objectForKey:@"txtMemCode"];

    NSLog(@"Load Class This is the memCode:%@", sMemCode);
    NSLog(@"Load Class This is the latitude:%@", latitude);
    NSLog(@"Load Class This is the longitude:%@", longitude);

    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    sURL = appDelegate.gURL;
    sURL = [sURL stringByAppendingString:@"/apps/class.asp?"];
    sURL = [sURL stringByAppendingString:@"memCode="];
    sURL = [sURL stringByAppendingString:sMemCode];
    sURL = [sURL stringByAppendingString:@"&dtpClass="];
    sURL = [sURL stringByAppendingString:sDate];
    sURL = [sURL stringByAppendingString:@"&lat="];
    sURL = [sURL stringByAppendingString:latitude];
    sURL = [sURL stringByAppendingString:@"&long="];
    sURL = [sURL stringByAppendingString:longitude];

    NSLog(@" The sURL to load for the current page : %@ ", sURL);

    NSURL *url = [NSURL URLWithString:sURL];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [webView loadRequest:urlRequest];
    [webView setDelegate:(id<UIWebViewDelegate>)self];

}

解决方案

 I have put the `Location Delegates` to `AppDelegates` 

AppDelegates.h

 #import <UIKit/UIKit.h>
 #import<CoreLocation/CoreLocation.h>

 @interface AppDelegate : UIResponder <UIApplicationDelegate>{
CLLocationManager *locationManager;

}

@property (nonatomic, strong) NSString *slatitude;
@property (nonatomic, strong) NSString *slongitude;

@end

AppDelegates.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//--- Get current location ---
if (locationManager == nil)
{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    locationManager.delegate = self;

    //-- Pop up authrorization to use current location ---
    [locationManager requestAlwaysAuthorization];
}

[locationManager startUpdatingLocation];
}

- (void)locationManager: (CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation: (CLLocation *)oldLocation
{

float latitude = newLocation.coordinate.latitude;
slatitude = [NSString stringWithFormat:@"%f",latitude];
float longitude = newLocation.coordinate.longitude;
slongitude = [NSString stringWithFormat:@"%f", longitude];

NSLog(@"App:This is the latitude%@", slatitude);
NSLog(@"App:This is the longitude%@", slongitude);

}

- (void)locationManager:(CLLocationManager *)manager
   didFailWithError:(NSError *)error
{
    NSLog(@"Cannot find the location.");
}

In any VC,


 appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

latitude = appDelegate.slatitude;
longitude = appDelegate.slongitude;

实际上,您正在调用 ViewWillAppear 中的方法,并在 didUpdateLocations 中获取数据。无法保证 ViewWillappear 之后会调用,最好是在收到数据后调用 didUpdateLocations 中的方法

我建议您将 Location Delegates 代码移动到您的 Appdelegate 文件,以便它注册并不断更新到 location delegate 方法,

您可以从您的 appdelegate 文件中制作两个 属性 变量并在调用委托时不断更新它们,或者制作一个 getter 或 setter 方法,如下所示:

@interface AppDelegate : UIResponder<UILocationDelegate>{
 CLLocationManager * locationManager;
}
@property (nonatomic, strong) NSString *lattitude;
@property (nonatomic, strong) NSString *longitude;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
 if (locationManager == nil)
    {
        locationManager = [[CLLocationManager alloc] init];
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        locationManager.delegate = self;
        [locationManager requestAlwaysAuthorization];
    }

    [locationManager startUpdatingLocation];
}

然后在此处自己实现位置委托方法

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
      if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];
            self.latitude = [NSString stringWithFormat:@"%f",newLocation.coordinate.latitude];
            self.longitude = [NSString stringWithFormat:@"%f",newLocation.coordinate.longitude];
            state = placemark.administrativeArea;
            country = placemark.country;

            NSLog(@"This is the latitude%@", latitude);
            NSLog(@"This is the longitude%@", longitude);

        }

}

- (void)locationManager:(CLLocationManager *)manager
   didFailWithError:(NSError *)error
{
    NSLog(@"Cannot find the location.");
}

迟到你可以从你的 ViewController 作为

访问这个
- (void)viewDidAppear:(BOOL)animated {
AppDelegate* appdelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

NSString *lat = appdelegate.lattitude;
NSString *long = appdelegate.longitude;

}

通过这种方式,即使您切换标签栏或更改控制器,您仍将拥有最新的位置。