vandadnp / iOS-8-Swift-Programming-Cookbook

This is the GitHub repository of O'Reilly's iOS 8 Swift Programming Cookbook
1.35k stars 481 forks source link

getLocation with timer #11

Open kshysius opened 9 years ago

kshysius commented 9 years ago

Hi, I use "Handling Location Changes in the Background" examples

On simulator works fine but on device not working I use simulator iPhone 6 iOS 8.3 and device iPhone 6 iOS 8.3 On device when i click menu button i get location but after 30 seconds i can't get location

i need realy big help...

location services enabled

i add NSTimer

code:

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,
CLLocationManagerDelegate {

  var window: UIWindow?
  var locationManager: CLLocationManager! = nil
  var isExecutingInBackground = false

  func locationManager(manager: CLLocationManager!,
    didUpdateToLocation newLocation: CLLocation!,
    fromLocation oldLocation: CLLocation!){
      if isExecutingInBackground{
        println(newLocation);
        locationManager.stopUpdatingLocation()
      } else {
        /* We are in the foreground. Do any processing that you wish */
      }
  }

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
 {
    locationManager = CLLocationManager()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.delegate = self
    locationManager.startUpdatingLocation()
    return true
  }

  func applicationDidEnterBackground(application: UIApplication) {
    isExecutingInBackground = true
    var timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: Selector("update"), userInfo: nil, repeats: true)

    /* Reduce the accuracy to ease the strain on
    iOS while we are in the background */
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
  }

    func update() {
        println("test");
        locationManager.startUpdatingLocation()
    }

  func applicationWillEnterForeground(application: UIApplication) {
    isExecutingInBackground = false

    /* Now that our app is in the foreground again, let's increase the location
    detection accuracy */
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
  }
}