Created
January 18, 2017 14:53
-
-
Save lukewakeford/453b543d067b80604ca965694ee105ca to your computer and use it in GitHub Desktop.
BackgroundLocation.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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