获取当前位置而不是缓存 ios

Getting Current Location instead of Cache ios

我搜索了很多但没有得到任何满意的答案,我有一个场景,我正在根据用户的当前位置显示卖家列表。我是第一次获取位置,之后当我 运行 我的应用程序每当我尝试获取位置时,我都会获取缓存位置数据。我确实在每 24 小时后尝试了一段时间,但仍然获得了我当前位置也发生变化的缓存位置。以下是我用来参考的代码。请指教

属性 在头文件中定义

@property (nonatomic,retain) CLLocationManager *locationManager;

- (void)startSingleLocationRequest
{       
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

    [self.locationManager startUpdatingLocation];
    [self.locationManager requestWhenInUseAuthorization];


}

#pragma mark --didUpdateLocations
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{



    self.latitudeValue =  locations.lastObject.coordinate.latitude;
    self.longitudeValue =  locations.lastObject.coordinate.longitude;
// location set for simulation to UK
    if(self.latitudeValue != 51.509979 && self.longitudeValue != -0.133700){
         [MBProgressHUD hideHUDForView:self.outletSearchNearBy animated:YES];
           [self.locationManager stopUpdatingLocation];
        abc *slv =[self.storyboard instantiateViewControllerWithIdentifier:@"abc"];
        slv.receivedLatitudeValue = self.latitudeValue;
        slv.receivedLongitudeValue = self.longitudeValue;

        [self.navigationController pushViewController:slv animated:YES];
    }
    else{}

}

你可以这样做,

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

for(int i=0;i<locations.count;i++){
    CLLocation * newLocation = [locations objectAtIndex:i];
    CLLocationCoordinate2D theLocation = newLocation.coordinate;
    CLLocationAccuracy theAccuracy = newLocation.horizontalAccuracy;

    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];

    if (locationAge > 5.0)
    {
        continue;
    }



       // do your all stuff here and then

       break;

    }


}

如果您的位置时效超过 5 秒,您的代码将不会执行。您可以决定位置时长是10秒还是20秒!

更新:

只需替换您的 属性 声明

 @property (nonatomic,retain) CLLocationManager *locationManager;

 @property (nonatomic,strong) CLLocationManager *locationManager;

只需将其声明为实例变量,如

 CLLocationManager *locationManager;

并从它的每个实例中删除 self!

第二件事,

你应该先做,

  [self.locationManager requestWhenInUseAuthorization];

然后开始更新位置,

  [self.locationManager startUpdatingLocation];

你能这样试试吗

self.locationManager.pausesLocationUpdatesAutomatically = NO;

因为它

  • 指定可能会自动暂停位置更新。
  • 默认情况下,对于链接到 iOS 6.0 或更高版本的应用程序,这是 YES。

另一方面,kCLLocationAccuracyBestForNavigation 使用极速 GPS。所以最好使用它而不是 kCLLocationAccuracyNearestTenMeters.

Lion 感谢您的支持,实际上我正在检查广场内的位置,由于我没有找到正确的位置,我在外面进行了测试,它显示完美。无论如何,谢谢狮子,你真的很有帮助。