Swift 位置管理器

Vyk*_*tas 4 iphone location cllocationmanager ios swift

我在 Swift 中的位置有问题。

在模拟器上工作正常但在设备上不起作用

我使用模拟器 iPhone 6 iOS 8.3 和设备 iPhone 6 iOS 8.3

我的代码:

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,
CLLocationManagerDelegate {

  var window: UIWindow?
  var locationManager: CLLocationManager! = nil
  var isExecutingInBackground = false

  func locationManager(manager: CLLocationManager!,
    didUpdateToLocation newLocation: CLLocation!,
    fromLocation oldLocation: CLLocation!){
      if isExecutingInBackground{
        println(newLocation);
        locationManager.stopUpdatingLocation()
      } else {
        /* We are in the foreground. Do any processing that you wish */
      }
  }

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
 {
    locationManager = CLLocationManager()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.delegate = self
    locationManager.startUpdatingLocation()
    return true
  }



  func applicationDidEnterBackground(application: UIApplication) {
    isExecutingInBackground = true
    var timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: Selector("update"), userInfo: nil, repeats: true)


    /* Reduce the accuracy to ease the strain on
    iOS while we are in the background */
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
  }

    func update() {
        println("test");
        locationManager.startUpdatingLocation()
    }

  func applicationWillEnterForeground(application: UIApplication) {
    isExecutingInBackground = false

    /* Now that our app is in the foreground again, let's increase the location
    detection accuracy */
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
  }
}
Run Code Online (Sandbox Code Playgroud)

我想每 30 秒获取一次位置信息

那么为什么不在设备上工作呢?

Rob*_*Rob 5

底线,对于后台更新,您要么使用“重大更改”服务,要么必须请求后台位置服务(Apple 将其限制为对位置更新有迫切需求的应用程序,即实际导航应用程序)。

请参阅iOS 应用程序编程指南中的跟踪用户位置部分

跟踪用户的位置

有几种方法可以在后台跟踪用户的位置,其中大多数实际上并不需要您的应用程序在后台连续运行:

  • 显着变化定位服务(推荐)
  • 仅前台位置服务
  • 后台定位服务

对于不需要高精度位置数据的应用,强烈推荐使用显着变化位置服务。使用此服务,仅当用户位置发生显着变化时才会生成位置更新;因此,它非常适合社交应用程序或为用户提供非关键位置相关信息的应用程序。如果应用在更新时挂起,系统会在后台唤醒它来处理更新。如果应用程序启动此服务然后终止,系统会在新位置可用时自动重新启动应用程序。此服务在 iOS 4 及更高版本中可用,并且仅在包含蜂窝无线电的设备上可用。

仅前台和后台位置服务都使用标准的位置核心位置服务来检索位置数据。唯一的区别是,如果应用程序被暂停,仅前台的位置服务将停止提供更新,如果应用程序不支持其他后台服务或任务,则可能会发生这种情况。仅前台位置服务适用于仅在前台运行时需要位置数据的应用程序。

您可以从 Xcode 项目中功能选项卡的背景模式部分启用位置支持。(您也可以通过UIBackgroundModes在您的应用程序Info.plist文件中包含带有位置值的键来启用此支持。)启用此模式不会阻止系统挂起应用程序,但它会告诉系统它应该在任何时候唤醒应用程序要提供的新位置数据。因此,此键有效地让应用程序在后台运行,以便在发生位置更新时进行处理。

重要提示:鼓励您谨慎使用标准服务或改用重要的位置更改服务。定位服务需要积极使用 iOS 设备的板载无线电硬件。连续运行此硬件会消耗大量电量。如果您的应用不需要向用户提供精确且连续的位置信息,则最好尽量减少使用位置服务。

有关如何在您的应用程序中使用每个不同位置服务的信息,请参阅位置和地图编程指南。