在iOS 9.3中杀死/终止应用程序后,为什么后台位置不起作用

时间:2016-07-11 04:57:31

标签: iphone swift swift2 core-location ios9.3

kill / Terminate应用程序后后台位置无法正常工作。我在我的应用程序中使用NSLocationAlwaysUsageDescription和后台提取也来自Capabilities,这里我的代码是:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate{

    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 1000.0
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.startUpdatingLocation()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


   func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
            CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){

           let currentLocation = manager.location
            let notification = UILocalNotification()
            notification.alertBody = " Lat \(currentLocation?.coordinate.latitude), Long \(currentLocation?.coordinate.longitude)"
            notification.soundName = UILocalNotificationDefaultSoundName
            UIApplication.sharedApplication().scheduleLocalNotification(notification)

            print(" Lat \((currentLocation?.coordinate.latitude))!, Long \((currentLocation?.coordinate.longitude))!")
        }

    }

}

这个代码在单击主页按钮时工作但是在这种情况下终止/终止应用程序不能正常工作后请在这里给我解决方案我错过了我的代码。

1 个答案:

答案 0 :(得分:1)

经过一些更改后,我通过执行此更改获得了解决方案,并且代码在后台模式和前台模式下正常工作,现在可以获取位置。

Swift 3

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = 2000
    if #available(iOS 9.0, *) {
        locationManager.allowsBackgroundLocationUpdates = true
    }
    locationManager.startMonitoringSignificantLocationChanges()
    locationManager.pausesLocationUpdatesAutomatically = true
    locationManager.requestAlwaysAuthorization()