【问题标题】:CLLocationManager does not initialize on viewDidLoadCLLocationManager 未在 viewDidLoad 上初始化
【发布时间】:2015-02-17 11:29:50
【问题描述】:

我有一个带有UIWebView 的简单objective C 应用程序。这是在 viewDidLoad 方法中加载一个 URL,我需要将此 URL 本地化 BEFORE loadRequest 但我的 CLLocationManager 正在调用 didUpdateToLocation 方法 AFTER loadRequest.

我的viewDidLoad 方法:

- (void)viewDidLoad {
    // execute super method
    [super viewDidLoad];

    // put gray background color
    self.view.backgroundColor = [UIColor lightGrayColor];

    // define itself as UIWebView delegate
    self.webView.delegate = self;

    // define itself as CLLocationManager delegate
    locationManager = [[CLLocationManager alloc] init];

    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];

    NSLog(@"LOCALIZED????%@",[self getCustomURL:homeURL]);
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[self getCustomURL:homeURL]]]];
}

我在调用loadRequest 时总是得到 (null),但在我得到正确的位置之后。

我试图在一个新线程中分离startUpdatingLocation

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    [locationManager startUpdatingLocation];
});

或者等到找到正确的位置:

while (longitude == nil) {
    [locationManager startUpdatingLocation];
}

知道如何获取loadRequest 之前的位置以获取网址

【问题讨论】:

    标签: ios objective-c iphone xcode geolocation


    【解决方案1】:

    CLLocationManager 是一个异步任务。定位后执行loadRequest,需要为CLLocationManager实现delegate,然后在webview上调用loadRequest

    【讨论】:

      【解决方案2】:

      您可以在 CLLocationManagerDelegate 的方法中使用 loadRequest:

      - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
          ……
          ……
          [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[self getCustomURL:homeURL]]]];
          ……
          ……
      }
      

      另外,在 iOS8 中,您需要做几件事来获取位置:

      1) 在 startUpdatingLocation 之前调用 requestWhenInUseAuthorization 方法:

      if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
         [locationManager requestWhenInUseAuthorization];
      }
      [locationManager startUpdatingLocation];
      

      2)NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 键添加到 Info.plist。

      【讨论】:

        猜你喜欢
        • 2011-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多