快速获取期间位置

时间:2015-05-21 12:40:18

标签: ios swift location task

我使用这个例子: http://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial

我想在Swift上每隔两分钟在后台获取用户位置

我的修改代码:

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)
    }
  }
}

添加计时器

 @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()
    }
  }

添加"测试" FUNC

func test(){
  locationManager.startUpdatingLocation()
}

和乐趣" locationManager"添加

locationManager.stopUpdatingLocation()
在ios模拟器上我每隔两分钟获取一次位置,但是手机无法工作......为什么?

0 个答案:

没有答案