后台位置更新无效

时间:2016-07-19 12:54:01

标签: ios swift core-location

我正在尝试为位置实现后台提取,它在iOS模拟器内部工作得很完美,但是当我在手机上构建它时,它似乎不起作用。这是我目前的代码:

import UIKit
import CoreLocation

class CurrentConditonsViewController: UIViewController, CLLocationManagerDelegate {

lazy var locationManager: CLLocationManager! = {
    let manager = CLLocationManager()
    manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    manager.delegate = self
    manager.requestAlwaysAuthorization()
    manager.distanceFilter = 2000
    if #available(iOS 9.0, *) {
        manager.allowsBackgroundLocationUpdates = true
    } else {
        // Fallback on earlier versions
    };
    return manager
}()    
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
var userLocation : String!
var userLatitude : Double!
var userLongitude : Double!
var userTemperatureCelsius : Bool!


override func viewDidLoad() {
    locationManager.startUpdatingLocation();

    refresh()

}

func refresh(){
    initLocationManager()
}

func initLocationManager() {
    seenError = false
    locationFixAchieved = false
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
}

func displayLocationInfo(placemark: CLPlacemark?) {
    if let containsPlacemark = placemark {
        //stop updating location to save battery life
        locationManager.stopUpdatingLocation()
        let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
        let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
        //println(locality)
        //println(postalCode)
        //println(administrativeArea)
        //println(country)

    }
}

// MARK: - CLLocationManagerDelegate

func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
    // Add another annotation to the map.
   let coords =  newLocation.coordinate
    userLatitude = coords.latitude
    userLongitude = coords.longitude

    if UIApplication.sharedApplication().applicationState == .Active {
        NSLog("App is in foreground. New location is %@", newLocation)
        CLGeocoder().reverseGeocodeLocation(newLocation, completionHandler: {(placemarks, error) -> Void in
            if error != nil {
                print("Reverse geocoder failed with error" + error!.localizedDescription)
                return
            }

            if placemarks!.count > 0 {
                let pm = placemarks![0]
                self.displayLocationInfo(pm);

            } else {
                print("Problem with the data received from geocoder")
            }


        })


    } else {
        NSLog("App is backgrounded. New location is %@", newLocation)
        let coord = newLocation.coordinate
        let lat = coord.latitude.description;
        let lng = coord.longitude.description;
        let localNotification:UILocalNotification = UILocalNotification()
        localNotification.alertAction = "Project RainMan"
        localNotification.alertBody = "Location Updated: " + lat + ", " + lng
        localNotification.fireDate = NSDate(timeIntervalSinceNow: 8)
        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

    }
}

func locationManager(manager: CLLocationManager,
                     didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    var shouldIAllow = false
    var locationStatus = ""
    switch status {
    case CLAuthorizationStatus.Restricted:
        locationStatus = "Restricted Access to location"
    case CLAuthorizationStatus.Denied:
        locationStatus = "User denied access to location"
    case CLAuthorizationStatus.NotDetermined:
        locationStatus = "Status not determined"
    default:
        locationStatus = "Allowed to location Access"
        shouldIAllow = true
    }
    NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
    if (shouldIAllow == true) {
        NSLog("Location to Allowed")
        // Start location services
        if #available(iOS 9.0, *) {
            locationManager.allowsBackgroundLocationUpdates = true
        } else {
            // Fallback on earlier versions
        };
        locationManager.startUpdatingLocation()
    } else {
        NSLog("Denied access: \(locationStatus)")
    }
}
} // END OF CLASS

我的实际设备上没有收到任何通知,值得注意的是,今天早上代码只会在应用运行时更新应用。我已经花了几天时间来研究这段代码,并确信它很简单,任何帮助都会非常感谢!

0 个答案:

没有答案