我有一个带有objective C的简单UIWebView应用。这正在viewDidLoad方法中加载URL,我需要在loadRequest之前本地化此URL,但是我的CLLocationManagerdidUpdateToLocation之后调用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之前具有URL的位置

最佳答案

您可以在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)将NSLocationAlwaysUsageDescription或NSLocationWhenInUseUsageDescription键添加到Info.plist。

关于ios - CLLocationManager不会在viewDidLoad上初始化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28560922/

10-08 22:02