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

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れますが、場所を取得した後に削除するため、場所を取得するのは 1 回だけです。

編集:notificationobserverパターンを追加する必要がないように、このヘルパークラスを屈折させました

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)

    }
}

ユーザー権限を取得する必要があるView 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

アニッシュの答えを補足するために、ヘルパー クラスが位置情報の更新を呼び出さなかったとき (つまり、位置情報サービスをオフにしたとき) を知りたい場合は、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 に答える