【发布时间】:2017-05-22 08:25:10
【问题描述】:
当我的应用程序处于后台或被终止时,我希望每 1 分钟获取一次新位置。 这是我的代码:
定位服务:
class LocationService: NSObject, CLLocationManagerDelegate {
static let shared = LocationService()
var locationManager = CLLocationManager()
var significatLocationManager = CLLocationManager()
var currentLocation: CLLocation!
var timer = Timer()
var bgTask = UIBackgroundTaskInvalid
func startUpdatingLocation() {
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
if #available(iOS 9.0, *) {
locationManager.allowsBackgroundLocationUpdates = true
}
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
func stopUpdatingLocation() {
locationManager.stopUpdatingLocation()
timer.invalidate()
}
func restartUpdatingLocation() {
locationManager.stopMonitoringSignificantLocationChanges()
timer.invalidate()
startUpdatingLocation()
}
func startMonitoringLocation() {
locationManager.stopUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
timer.invalidate()
}
func changeLocationAccuracy(){
switch locationManager.desiredAccuracy {
case kCLLocationAccuracyBest:
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.distanceFilter = 99999
case kCLLocationAccuracyThreeKilometers:
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
default: break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.bgTask)
self.bgTask = UIBackgroundTaskInvalid
})
currentLocation = locations.last!
let interval = currentLocation.timestamp.timeIntervalSinceNow
let accuracy = self.locationManager.desiredAccuracy
if abs(interval) < 60 && accuracy != kCLLocationAccuracyThreeKilometers {
timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(LocationService.changeLocationAccuracy), userInfo: nil, repeats: false)
changeLocationAccuracy()
}
}
}
应用委托:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if launchOptions?[UIApplicationLaunchOptionsKey.location] != nil {
LocationService.shared.restartUpdatingLocation()
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
LocationService.shared.restartUpdatingLocation()
}
func applicationWillTerminate(_ application: UIApplication) {
LocationService.shared.startMonitoringLocation()
}
视图控制器:
override func viewDidLoad() {
LocationService.shared.startUpdatingLocation()
}
但是我的代码不起作用,当我的应用程序在后台运行几分钟后,我没有得到新的位置。当我的应用程序被暂停或终止时也是如此。 有什么解决办法吗?请不要说我使用的是 Swift 3 和 xcode 8.1。
提前致谢
【问题讨论】:
-
你必须走很远才能获得重要的位置变化。至少 >500 米。
-
这是我的应用程序被杀死的时候。但是我如何才能每 1 分钟在后台无限期地更新位置?
-
你不能。你可以尝试滥用
backgroundFetch。
标签: ios swift3 xcode8 cllocation