iphoneswiftswift2core-locationios9.3

Why background location is not working after kill/Terminate app in iOS 9.3


Background location not working after kill/ Terminate application. I am using in my application NSLocationAlwaysUsageDescription and Background fetch also on from Capabilities, here my code is :

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))!")
        }

    }

}

this code is working when click home button but after terminate/kill app in this condition not working please give me the solution here what i missed inside my code.


Solution

  • After some changes i got solution my self by doing this changes and code working fine in background mode and foreground mode now able to fetch location.

    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()