为什么我无法获得位置?

时间:2015-06-03 23:17:11

标签: swift location

我想得到我的位置坐标。出于任何原因,我的loactionManger:didUpdateLocations无效。我希望你能提供帮助。

import CoreLocation
class Location: NSObject , CLLocationManagerDelegate {
    let locationManager = CLLocationManager()
    var latitude = 0.0
    var longitude = 0.0
    func getLocation() -> (latitude:Double , longitude: Double ){
        if(CLLocationManager.locationServicesEnabled()){
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
            locationManager.requestWhenInUseAuthorization()
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
        return (latitude, longitude)
    }
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var location :CLLocationCoordinate2D = manager.location.coordinate
        latitude = location.latitude
        longitude = location.longitude
        println("Location: latitude: \(latitude)")
        println("Location: longitude: \(longitude)")
        locationManager.stopUpdatingLocation()
    }
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        println("Error while updating location" + error.localizedDescription)
    }
}

1 个答案:

答案 0 :(得分:1)

这是一个有效的例子。检查框架可以返回的各种授权和错误。

要记住的一件事:需要强力保留实施CLLocationManagerDelegate的对象。一旦对象变为deinit,你的委托调用就会停止。

用法:ctor创建对象,如果要在委托方法中流式传输位置数据(未提供流式传输代码),请在客户端中调用startObserving()stopObserving()。使用getCurrentLocation()获取一次性值。

import CoreLocation

let DEFAULT_LOCATION_ACCURACY = kCLLocationAccuracyHundredMeters

struct LocationOptions {
    var accuracy: Double

    init(enableHighAccuracy: Bool = true) {
        accuracy = enableHighAccuracy ? kCLLocationAccuracyBest : DEFAULT_LOCATION_ACCURACY
    }
}

let loc = LocationOptions(enableHighAccuracy: false)

class LocationObserver: NSObject, CLLocationManagerDelegate {

    var _locationManager = CLLocationManager()
    var _observingLocation: Bool?
    var _observerOptions: LocationOptions?

    // Lifecycle

    init(accuracy: Bool = true) {
        super.init()
        _locationManager.delegate = self
        _locationManager.distanceFilter = DEFAULT_LOCATION_ACCURACY
        _observerOptions = LocationOptions(enableHighAccuracy: accuracy)
    }

    deinit {
        _locationManager.stopUpdatingLocation()
        _locationManager.delegate = nil
    }

    // Private API

    private func beginLocationUpdates() {

        // Request location access permission
        _locationManager.requestWhenInUseAuthorization()

        // Start observing location
        _locationManager.startUpdatingLocation()
    }

    // Public API

    func startObserving() {

        _locationManager.desiredAccuracy = _observerOptions!.accuracy
        beginLocationUpdates()
        _observingLocation = true
    }

    func stopObserving() {
        // Stop observing
        _observingLocation = false

        // Stop updating if no pending requests
        _locationManager.stopUpdatingLocation()
    }

    func getCurrentPosition(options: LocationOptions) {

        if !CLLocationManager.locationServicesEnabled() {
            NSLog("Location services disabled.")
            return
        }

        if CLLocationManager.authorizationStatus() == .Denied {
            return
        }

        // Configure location manager and begin updating location
        _locationManager.desiredAccuracy = min(_locationManager.desiredAccuracy, options.accuracy)
        beginLocationUpdates()
    }

    // CLLocationManagerDelegate
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) {

        // Get location data
        let location = locations[locations.count - 1] as! CLLocation

        // latitude:         location.coordinate.latitude,
        // longitude:        location.coordinate.longitude,
        // altitude:         location.altitude,
        // accuracy:         location.horizontalAccuracy,
        // altitudeAccuracy": location.verticalAccuracy,
        // heading:          location.course,
        // speed:            location.speed,

        //
        // STORE LOCATION DATA INSIDE SOME STRUCTURE HERE.
        // 

        // Stop updating if not observing
        if !(_observingLocation!) {
            _locationManager.stopUpdatingLocation()
        }

        // Reset location accuracy
        _locationManager.desiredAccuracy = DEFAULT_LOCATION_ACCURACY
    }

}

// Usage
let locObs = LocationObserver() // Location Observer with high accuracy by default

locObs.startObserving() // Start observing

// Gather data inside the CLLocationManagerDelegate locationManager:didUpdateLocations: method

locObs.stopObserving() // Stop observing


// Alternative to start/stop. get one time location with low accuracy (for example)
locObs.getCurrentPosition(LocationOptions(enableHighAccuracy: false))