获得一定时间之间的位置swift

时间:2015-09-16 17:10:52

标签: ios swift

我正在尝试将经度和纬度存储在数据库中。我想在上午8:00到下午7:00之间获取用户位置,无论应用程序是在前景还是后台。下面是我的代码,到目前为止在地图上注释位置,如果它在后台,而不是在控制台中记录它

import UIKit
import CoreLocation
import MapKit

class ViewController: 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!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        locationManager.startUpdatingLocation()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    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 {
            NSLog("App is backgrounded. New location is %@", newLocation)
        }
    }


}

1 个答案:

答案 0 :(得分:0)

您无法在预定时间启动位置服务。如果您需要在应用程序处于后台时知道位置,则需要始终保持位置服务的运行。

但除非您的应用是绝对需要持续,非常准确的后台定位服务的正确导航应用,否则您无法在后台运行标准位置服务。你通常也不想这样做,因为这会杀死电池。

但是,你可以做的是保持"重大改变"位置服务运行。即使这种不太准确,电池消耗较低的服务也会对电池产生影响,但它不会像标准位置服务那样快速耗尽电池。但它仍然会对电池产生负面影响(因为你的应用程序会每次用户更换手机信号塔,而不仅仅是在特定时间),所以除非这是应用程序的一个重要功能,否则你可能不会想要做到这一点。

这是一种啰嗦的方式,说你不能轻易做你所要求的。