I use this example: http://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial
i want get user location in background every two minutes on Swift
My modification code:
class LocationViewController: UIViewController, CLLocationManagerDelegate {
var locations = [MKPointAnnotation]()
lazy var locationManager: CLLocationManager! = {
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
manager.requestAlwaysAuthorization()
return manager
}()
@IBOutlet weak var mapView: MKMapView!
@IBAction func enabledChanged(sender: UISwitch) {
if sender.on {
var timer = NSTimer.scheduledTimerWithTimeInterval(120, target: self, selector: Selector("test"), userInfo: nil, repeats: true)
} else {
locationManager.stopUpdatingLocation()
}
}
@IBAction func accuracyChanged(sender: UISegmentedControl) {
let accuracyValues = [
kCLLocationAccuracyBestForNavigation,
kCLLocationAccuracyBest,
kCLLocationAccuracyNearestTenMeters,
kCLLocationAccuracyHundredMeters,
kCLLocationAccuracyKilometer,
kCLLocationAccuracyThreeKilometers]
locationManager.desiredAccuracy = accuracyValues[sender.selectedSegmentIndex];
}
func test(){
locationManager.startUpdatingLocation()
}
// MARK: - CLLocationManagerDelegate
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)
} else {
locationManager.stopUpdatingLocation()
NSLog("App is backgrounded. New location is %@", newLocation)
}
}
}
add timer
@IBAction func enabledChanged(sender: UISwitch) {
if sender.on {
var timer = NSTimer.scheduledTimerWithTimeInterval(120, target: self, selector: Selector("test"), userInfo: nil, repeats: true)
} else {
locationManager.stopUpdatingLocation()
}
}
add "test" func
func test(){
locationManager.startUpdatingLocation()
}
and in fun "locationManager" add
locationManager.stopUpdatingLocation()
on ios emulator i get location every two minutes, but on phone not working... why?