当用户点击按钮时,我希望我的应用获取当前位置。 我在init方法中初始化locationManager对象。

第一个问题:如果每次按下按钮都需要当前位置,这会很好吗? 还是应该在viewDidLoad初始化它?

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self)
    {
        // Create location manager object
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;

        // Best accuracy as posibble
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    }
    return self;
}

在我的委托方法中,我一获得currentLocation ,便立即stopUpdatingLocation

// Delegate method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray        
*)locations   
{
    CLLocation *currentLocation = [locations lastObject];

    [locationManager stopUpdatingLocation];
}

在这里,我使用按钮startUpdatingLocation

- (IBAction)getCurrentLocation:(id)sender
{
    [locationManager startUpdatingLocation];
}

第二个问题是:当我第一次按下按钮时,我得到了正确的位置,但是当我在模拟器中更改位置并再次按下时,它显示了第一个。 同样,当我按下按钮时,它会显示正确的按钮。 我试图在每次按下按钮时初始化locationManager但是那样也不行。

我在其他帖子上读到它是由于位置缓存或类似原因。 如何删除该缓存? 因为无论如何我都会将该位置存储在数据库中的其他位置,所以我不需要旧的位置。

===============>>#1 票数:1

问题1:我应该在initviewDidLoad初始化我的位置管理器

我会选择viewDidLoad ,只是因为这样可以确保所有依赖项都已加载。

问题2:用户位置未更新。

用户位置没有改变,因为您是在第一次收到位置信息后停止收听位置更新:

[locationManager stopUpdatingLocation];

但是,当用户按下getCurrentLocation按钮时,您将再次开始收听。 如果愿意,您仍然可以使用这种方法,但是我会在getCurrentLocation操作中设置一个标志,以在找到新位置时更新UI。

例:

// Delegate method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray        
*)locations   
 {
     CLLocation *currentLocation = [locations lastObject];

     [locationManager stopUpdatingLocation];

     if (self.updateUIOnNextLocation) {
         [self updateUIWithLocation:currentLocation];
         self.updateUIOnNextLocation = NO;
     }
}

...

- (IBAction)getCurrentLocation:(id)sender
{
     self.updateUIOnNextLocation = YES;
     [locationManager startUpdatingLocation];
}

===============>>#2 票数:0

如果您每次按键仅需要更新当前位置,为什么不创建一个单例类( 如下所示的基于iOS 8的示例 ),并缓存当前位置,然后添加一个“重新触发”方法,当用户按下该方法时会调用该方法一个告诉位置管理器再次开始更新位置,缓存结果然后关闭更新(再次)的按钮? 这样,您就不会浪费资源来获取不必要的更新。 您仍然必须以某种方式同步演示文稿,这样当位置不可用或当前位置不可用时,它就很明显或得到处理。

import Foundation
import CoreLocation

class CurrentLocation : NSObject, CLLocationManagerDelegate {

    enum InitPhase {
        case RequestingAuthorization, StartUpdatingLocation, ReverseGeocoding
    }

    var locationManager : CLLocationManager?
    var placemark : CLPlacemark?
    var initializationPhase : InitPhase = .RequestingAuthorization

    override init() {
        super.init()
        placemark = nil
        locationManager = CLLocationManager()
        locationManager!.delegate = self
        locationManager!.requestWhenInUseAuthorization()
    }

    func nonull(s : String?) -> String {
        if (s == nil) {
            return ""
        }
        return s!
    }

    // Handle all NSErrors here (not just from location manager)
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        switch(initializationPhase) {
        case .RequestingAuthorization:
            println("CurrentLocation class - App not authorized by user to use location services")
        case .StartUpdatingLocation:
            println("CurrentLocation class - StartUpdatingLocation\n   ClLocationManager reported error to delegate:\n      \(error.localizedDescription)")
        case .ReverseGeocoding:
            println("CurrentLocation class - ReverseGeocoding\n   CLGeocoder().reverseGeocodeLocation() error:\n      \(error.localizedDescription)")
        default:
            println("CurrentLocation class - Unknown basis\n   ClLocationManager reported error to delegate:\n      \(error.localizedDescription)")

        }
    }

    func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if (status == .AuthorizedAlways || status == .AuthorizedWhenInUse) {
            println("CurrentLocation class - App authorized to use location services")
            initializationPhase = .StartUpdatingLocation
            locationManager!.startUpdatingLocation()
        } else {
            println("CurrentLocation class - App not authorized by user to use location services")

        }
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var location = locations.last as CLLocation
        println("CurrentLocation class - CLLocation delagate received loocation update\n")
        locationManager?.stopUpdatingLocation()
        CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
            if (error == nil) {
                println("   Latitude/Longitude: \(location.coordinate.latitude) \(location.coordinate.longitude)")
                if placemarks.count > 0 {
                    self.placemark = CLPlacemark(placemark: placemarks[0] as CLPlacemark)
                    println(String(format:"   subThoroughfare:    %@\n   thoroughfare:       %@\n   locality:           %@\n   postalCode:         %@\n   administrativeArea: %@\n   country:            %@",
                                self.nonull(self.placemark!.subThoroughfare),
                                self.nonull(self.placemark!.thoroughfare),
                                self.nonull(self.placemark!.locality),
                                self.nonull(self.placemark!.postalCode),
                                self.nonull(self.placemark!.administrativeArea),
                                self.nonull(self.placemark!.country)))
                } else {
                    println("No placemarks located")
                }

            } else {
                self.locationManager(manager, didFailWithError: error)
            }
        })
    }
}

  ask by zhuber translate from so

未解决问题?本站智能推荐: