Skip to content

Instantly share code, notes, and snippets.

@amratab
Last active May 27, 2016 13:26
Show Gist options
  • Save amratab/40dabf65244108ecf388ca1befe6ff3d to your computer and use it in GitHub Desktop.
Save amratab/40dabf65244108ecf388ca1befe6ff3d to your computer and use it in GitHub Desktop.
Select the Info.plist file.
Click on the + button to add a key.
Add the key named NSLocationAlwaysUsageDescription.
Write a convincing description of why you need location in the background.
class MovieDetailViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var locations = [MKPointAnnotation]()
lazy var locationManager: CLLocationManager! = {
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
manager.requestAlwaysAuthorization()
manager.allowsBackgroundLocationUpdates = true
return manager
}()
@IBAction func enabledChanged(sender: UISwitch) {
if sender.on {
locationManager.startUpdatingLocation()
} else {
locationManager.stopUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
// Add another annotation to the map.
let annotation = MKPointAnnotation()
annotation.coordinate = newLocation.coordinate
// Also add to our map so we can remove old values later
locations.append(annotation)
// Remove values if the array is too big
while locations.count > 100 {
let annotationToRemove = locations.first!
locations.removeAtIndex(0)
// Also remove from the map
mapView.removeAnnotation(annotationToRemove)
}
if UIApplication.sharedApplication().applicationState == .Active {
mapView.showAnnotations(locations, animated: true)
print("Showing annotations!")
} else {
NSLog("App is backgrounded. New location is %@", newLocation)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment