【问题标题】:Is it possible to automatically call 'locationManager:didUpdateLocations:' delegate method after the user's current location changes?是否可以在用户当前位置更改后自动调用 'locationManager:didUpdateLocations:' 委托方法?
【发布时间】:2016-11-18 09:33:29
【问题描述】:

我正在开发一个即使在后台也需要不断更新用户位置的应用程序。使用CLLocationManager,是否可以在使用位置发生变化后自动调用locationManager:didUpdateLocations:委托方法。

【问题讨论】:

    标签: ios geolocation core-location cllocationmanager location-services


    【解决方案1】:

    您不应该手动调用CLLocationManagerlocationManager:didUpdateLocations: 代表。

    locationManager:didUpdateLocations: 本质上旨在提供延迟的 GPS 更新以节省电池。因此,如果您需要立即更新,请实施 locationManager:didUpdateToLocation:fromLocation: 而不是 locationManager:didUpdateLocations:.

    您需要做的就是创建一个CLLocationManager 对象的实例并调用它的startUpdatingLocation 方法。

     self.locationManager = [[CLLocationManager alloc] init]; 
     [self.locationManager startUpdatingLocation]
    

    之后,locationManager:didUpdateToLocation:fromLocation:会在用户位置发生变化时立即被调用。

    另外,由于您也需要定位背景,请不要忘记在 plist 中添加相关功能。另外,对于iOS9+,别忘了下面的sn-p

    if (SystemVersionGreaterThanOrEqualTo(@"9.0"))
    {
        self.locationManager.allowsBackgroundLocationUpdates = YES;
    }
    

    注意:如果你实现了locationManager:didUpdateLocations:locationManager:didUpdateToLocation:fromLocation:将不会被调用。所以不要同时实现它们,只实现你需要的一个。

    【讨论】:

    • 感谢更新,但 locationManager:didUpdateToLocation:fromLocation: 方法在 iOS 9.0 中已弃用
    • @SachinKumaram locationManager:didUpdateToLocation:fromLocation: 自 iOS 6 以来已被弃用。但它的支持尚未删除,因为我认为没有其他方法可以获得即时更新(locationManager:didUpdateLocations: 提供延迟更新)。我们仍然使用 locationManager:didUpdateToLocation:fromLocation: 在我们需要即时和准确位置更新的一堆应用程序中。
    【解决方案2】:

    您可以按照以下方式使用 CLLocationManager 类的 startUpdatingLocation() 方法

       [locationManager startUpdatingLocation];
    

    当您的 viewController 实例在内存中处于活动状态时,此方法将被调用,但在后台情况下,当其他应用程序没有获得有效的内存空间来执行时,操作系统 (iOS) 会在一段时间后从后台删除应用程序。

    对于后台执行,您可以按照以下方式将代码放入后台任务块中

    UIBackgroundTaskIdentifier taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
            // Uh-oh - we took too long. Stop task.
    
    
        }];
    
    // Perform task here
    // Your code
    
     if (taskId != UIBackgroundTaskInvalid) {
            [[UIApplication sharedApplication] endBackgroundTask:taskId];
        }
    

    希望对你有帮助:)

    【讨论】:

      【解决方案3】:

      你不需要打电话

      [LocationManager startUpdating];
      

      每次更新位置时,位置管理器都会提供一个简单的解决方案。 您将获得所需的功能

      self.locationManager.distanceFilter = 10.0f;
      

      //当位置更改为 10 米时,位置管理器会更新您。

      【讨论】:

      • 如果你抓住了 [locationManager stopUpdatingLocation] 将无法工作;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      相关资源
      最近更新 更多