1

我正在制作一个使用设备定位服务的应用程序。每次位置发生变化时,该服务都需要捕获位置,并且它应该在所有情况下(后台/前台/已终止)保持运行,所以我使用startMonitoringSignificantLocationChanges()方法,但是当我将它发送到后台时,它工作了一段时间,然后停止,之后它不会捕获任何位置。我移动了文档建议的距离以获取位置更新(500m),但没有任何反应。我可能做错了什么?注意:在模拟器上它可以完美运行,但是在物理设备上它不起作用。

Info.plist文件启用了背景设置

<key>UIBackgroundModes</key>
  <array>
    <string>fetch</string>
    <string>location</string>
  </array>

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if (launchOptions != nil) {
        let locationManager = CLLocationManager()
        locationManager.delegate = ViewController()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.activityType = CLActivityType.other
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.startUpdatingLocation()
    }

    return true
}

func applicationDidEnterBackground(_ application: UIApplication) {
    let locationManager = CLLocationManager()
    locationManager.delegate = ViewController()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.activityType = CLActivityType.other
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.startMonitoringSignificantLocationChanges()
}

ViewController.swift

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {    
    // Capture of new location 
}
4

2 回答 2

0

将此代码写入您的AppDelegate didFinishLaunchingWithOptions

  //location manager
  locationManager = CLLocationManager()
  locationManager.delegate = self
  locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
  locationManager.distanceFilter = kCLDistanceFilterNone;
  locationManager.requestAlwaysAuthorization()
  locationManager.allowsBackgroundLocationUpdates = true
  locationManager.startUpdatingLocation()

在您的第一个屏幕viewDidLoad()(或不在didEnterBackground中的任何地方)调用 locationManager.startMonitoringSignificantLocationChanges( )

于 2017-04-13T11:34:12.007 回答
0

在 plist 添加了这些

NSLocationAlwaysUsageDescription

NSLocationWhenInUseUsageDescription

在此处输入图像描述

  locationManager.requestAlwaysAuthorization()  // Add this Code 
  locationManager.requestWhenInUseAuthorization()
  locationManager.startUpdatingLocation()
于 2017-04-13T11:09:44.987 回答