6

当视图确实出现时,我开始更新当前位置,并在locationManager:didUpdateLocations:调用时停止更新位置。但是为什么locationManager:didUpdateLocations:总是被调用几次呢?我错过了什么?

#import "ViewController.h"

@interface ViewController (){
    CLLocationManager *locationManager; // location manager for current location
}
@end

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self startUpdatingCurrentLocation];
}

- (void)startUpdatingCurrentLocation
{
    if (!locationManager)
    {
        locationManager = [[CLLocationManager alloc] init];
        [locationManager setDelegate:self];
        locationManager.distanceFilter = 10.0f; // we don't need to be any more accurate than 10m
    }
    [locationManager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    [locationManager stopUpdatingLocation];
}
@end
4

3 回答 3

7

可能这取决于您为 locationManager 设置的准确性。您有 3 种 o 定位蜂窝无线电、WiFi 地图、GPS。如果您设置为最佳精度,则位置管理器将继续检查您的位置,如果精度更高的位置超出距离过滤器的范围,则将再次调用委托方法。

于 2013-04-18T07:35:39.713 回答
3

SWIFT版本

我做了一个助手类HelperLocationManager并添加了一个notification- observer模式

import UIKit
import CoreLocation



class HelperLocationManager: NSObject {

    var locationManager = CLLocationManager()
    static let sharedInstance = HelperLocationManager()
    var currentLocation :CLLocation?
    var notGotUserLocation = true

    override init() {

        super.init()

        var code = CLLocationManager.authorizationStatus()

        if code == CLAuthorizationStatus.NotDetermined {

            locationManager.requestAlwaysAuthorization()
            locationManager.requestWhenInUseAuthorization()

        }
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
        locationManager.delegate = self
        locationManager.distanceFilter = 100;

    }


}


extension HelperLocationManager: CLLocationManagerDelegate{


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

            var locValue = locations.last as! CLLocation
            println(locValue)
            self.currentLocation = locValue
            NSNotificationCenter.defaultCenter().postNotificationName("sendCurrentAddressToViewController", object:self.currentLocation)
            notGotUserLocation = false


    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {

        println("Your error is ", error.localizedDescription)

    }


}

现在,如果您的Viewcontroller班级需要该位置,则将观察员放在那里

var helperLocation:HelperLocationManager?

viewDidLoad作为_

     override func viewDidLoad() {

         helperLocation = HelperLocationManager()
         NSNotificationCenter.defaultCenter().addObserver(self, selector: "getCurrentAddressToViewController:", name: "sendCurrentAddressToViewController", object: nil)

  }

//和观察者作为

 func getCurrentAddressToViewController(notification: NSNotification) {

        currentLocation = notification.object as? CLLocation
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "sendCurrentAddressToViewController", object: nil)

    }

//虽然didUpdateLocation被多次调用你只得到一个时间位置,因为observer在你得到位置后删除。

编辑:我重构了这个助手类,这样你就不需要添加通知观察者模式

class HelperLocationManager: NSObject {

    private lazy var locationManager = CLLocationManager()
    static let sharedInstance = HelperLocationManager()
    var currentLocation :CLLocation?

    override init() {

        super.init()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
    }
}

extension HelperLocationManager: CLLocationManagerDelegate{

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

        switch status {

        case CLAuthorizationStatus.NotDetermined:

            locationManager.requestWhenInUseAuthorization()


        case CLAuthorizationStatus.Restricted:

            PrinterHelper.messagePrinter("Restricted Access to location")

        case CLAuthorizationStatus.Denied:

            PrinterHelper.messagePrinter("User denied access to location")

        case CLAuthorizationStatus.AuthorizedWhenInUse:

            if #available(iOS 9.0, *) {

                locationManager.requestLocation()

            } else {

                locationManager.startUpdatingLocation()
            }

        default:

            PrinterHelper.messagePrinter("default authorization")

        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let locValue = locations.last
        HelperLocationManager.sharedInstance.currentLocation =  locValue
        locationManager.stopUpdatingLocation()

    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {

        PrinterHelper.errorPrinter(error.localizedDescription)

    }
}

查看需要获取用户权限的Controller

var helperLocationManager:HelperLocationManager?

viewDidLoad作为_

     override func viewDidLoad() {

         helperLocationManager = HelperLocationManager.sharedInstance


  }

要获得您需要将单例属性currentLocation称为的位置

 if  let userCurentLoc = HelperLocationManager.sharedInstance.currentLocation{

           //userCurrentLoc is the user Location

        }
于 2015-08-19T06:50:48.623 回答
0

为了补充 Anish 的回答,如果您想知道您的助手类何时没有调用位置更新(即当您关闭位置服务时),您可以使用该locationManager:didChangeAuthorizationStatus:方法管理它,如果您的位置不允许,您可以打电话给另一个notification- observer

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    var shouldIAllow = false

    switch status {
    case CLAuthorizationStatus.Restricted:
        locationStatus = "Restricted Access to location"
    case CLAuthorizationStatus.Denied:
        locationStatus = "User denied access to location"
    case CLAuthorizationStatus.NotDetermined:
        locationStatus = "Status not determined"
    default:
        locationStatus = "Allowed to location Access"
        shouldIAllow = true
    }

    if (shouldIAllow == true) {
        print("Location to Allowed")
        // Start location services
        locationManager!.startUpdatingLocation()
    } else {
        print("Denied access: \(locationStatus)")
        NSNotificationCenter.defaultCenter().postNotificationName("deniedLocation", object:locationStatus)
    }
}
于 2016-01-14T10:26:34.013 回答