Skip to content

Instantly share code, notes, and snippets.

@lukewakeford
Created January 18, 2017 14:53
Show Gist options
  • Save lukewakeford/453b543d067b80604ca965694ee105ca to your computer and use it in GitHub Desktop.
Save lukewakeford/453b543d067b80604ca965694ee105ca to your computer and use it in GitHub Desktop.
BackgroundLocation.swift
// BackgroundLocation.swift
import Foundation
class LocationManger : NSObject, CLLocationManagerDelegate {
static let sharedManager = LocationManger()
var locationManager:CLLocationManager!
var lastTimestamp:NSDate!
override init() {
super.init()
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.pausesLocationUpdatesAutomatically = false
}
func startUpdatingLocation() {
if CLLocationManager.authorizationStatus() == .Denied {
print("Location services are disabled in settings.")
} else {
if #available(iOS 8.0, *) {
self.locationManager.requestAlwaysAuthorization()
}
if #available(iOS 9.0, *) {
self.locationManager.allowsBackgroundLocationUpdates = true
}
self.locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let mostRecentLocation = locations.last {
print("Current location: \(mostRecentLocation.coordinate.latitude), \(mostRecentLocation.coordinate.longitude)")
}
let now = NSDate()
let interval = self.lastTimestamp != nil ? now.timeIntervalSinceDate(self.lastTimestamp) : 0
if (self.lastTimestamp == nil || interval >= 5 * 60) {
self.lastTimestamp = now
print("Sending current location to web service.")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment