viewDidAppear在locationManager可以找到用户之前调用的方法

时间:2012-12-24 11:46:55

标签: iphone objective-c ios cllocationmanager locationmanager

我在我的应用locationManager中呼叫delegate,并在各种viewDidAppear的{​​{1}}方法中引用了getUserLatitude和getUserLongitude函数。

我的问题是我的viewControllers方法启动太快而viewDidAppear找不到用户,appDelegate得0.000000,latitude得0.000000。有谁知道我怎么解决这个问题?谢谢!

我的appDelegate采用以下定位方法构建:

longitude

我正在使用这段代码从appDelegate获取更新的位置:

- (NSString *)getUserCoordinates
{
    NSString *userCoordinates = [NSString stringWithFormat:@"latitude: %f longitude: %f", 
    locationManager.location.coordinate.latitude, 
    locationManager.location.coordinate.longitude];
    locationManager = [[CLLocationManager alloc] init];
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];
    return userCoordinates;
}

- (NSString *)getUserLatitude
{
    NSString *userLatitude = [NSString stringWithFormat:@"%f", 
    locationManager.location.coordinate.latitude];
    return userLatitude;
}

- (NSString *)getUserLongitude
{
    NSString *userLongitude = [NSString stringWithFormat:@"%f", 
    locationManager.location.coordinate.longitude];
    return userLongitude;
}

3 个答案:

答案 0 :(得分:1)

在位置管理器更新位置后,将调用委托,可在此处使用。在位置更新后,您将在didUpdateToLocation方法中获得控件

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"Success ");
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Failed %d",[error code]);

}

答案 1 :(得分:0)

我在一个应用程序中也面临同样的问题。首先分配CLLocationManager,为其设置delegate,然后调用可以解决问题的startUpdatingLocation方法。

    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];

设置委托后,它会调用其委托方法&给我们lattitude& longitude当前位置为。

//delegate method
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{    
    self.currentLat=newLocation.coordinate.latitude;
    self.currentLong=newLocation.coordinate.longitude;
    NSLog(@"appDelegate newLocation %f  %f",self.currentLat,self.currentLong);
}

答案 2 :(得分:0)

我通过这样做来解决这个问题。

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


     NSLog(@"Ahsan");
     if (!oldLocation ||
        (oldLocation.coordinate.latitude != newLocation.coordinate.latitude && 
         oldLocation.coordinate.longitude != newLocation.coordinate.longitude &&
         newLocation.horizontalAccuracy <= 100.0)) 
     {
        //Your code comes here...
     }
 }