【问题标题】:How to get location at AppDelegate, and pass the lat and long to another VC and load webview如何在 AppDelegate 获取位置,并将经纬度传递给另一个 VC 并加载 webview
【发布时间】:2018-02-28 06:48:21
【问题描述】:

已编辑

我已经设法通过使用this 获得了当前位置。之后,我尝试将 lat 和 long 作为字符串传递给另一个加载 webview 的方法。一个问题是每次我加载这个 VC 时,它都没有调用下面的方法

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

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

-(void)viewWillAppear:(BOOL)animated

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

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

当我单击其他选项卡控制器并单击此 VC 时会发生什么。 lat 和 long 会再次刷新吗?

- (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;

【问题讨论】:

    标签: ios objective-c webview cllocationmanager viewwillappear


    【解决方案1】:

    我建议您将您的位置委托代码移动到您的 Appdelegate 文件中,以便它注册并不断更新到位置委托方法,

    您可以从您的 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;
    
    }
    

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 它仍然会调用 [self setupSegmentButtons];和 [self LoadClasses:dateString];如果 LoadClasses lat 和 long 为 nil,它将返回错误。我不知道为什么方法 didUpdateLocations 至少持续了 7 次,需要所有专家的帮助,谢谢。
      • 您可以获取一些布尔变量并在成功后停止它。通常即使您调用 stopUpdateservice,它也会调用 3-4 次
      猜你喜欢
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      相关资源
      最近更新 更多