I need to get current user location but I don't know if it has changed or not. Can I request a forced location update from CLLocationManager? 开发者_开发百科Or is there any other way to do that?
Stopping and restarting the LocationManager should force the device to re-acquire an initial position.
[locationManager stopUpdatingLocation];
[locationmanager startUpdatingLocation];
I have had the same problem in one of my apps. I actually had to change the app structure. This is what I have done: This class has a public method. -(void)locateMe; an abstract class needs to instantiate this class and run the locateMe then when userIsLocated a notification will be broadcasted. and another method can get the result coordinates from (CLLocation *)currentLocation;
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface ManageUserLocation : NSOperation <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *currentLocation;
-(void) locateMe;
@end
in the .m
#import "ManageUserLocation.h"
@implementation ManageUserLocation
@synthesize locationManager;
@synthesize currentLocation; // Other classes use this to get the coordination even better you can make another method that even dont get the direct access to currentLocation. It is up to you.
- (id)init
{
self = [super init];
if (self) {
//[self locateMe]; // Just a hook if you need to run it
}
return self;
}
-(void) locateMe {
self.locationManager = nil;
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// User location has been found/updated, load map data now.
[self.locationManager stopUpdatingLocation];
currentLocation = [newLocation copy];
// WooHoo Tell everyone that you found the userLocation
[[NSNotificationCenter defaultCenter] postNotificationName:@"userLocationIsFound" object:nil];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
// Failed to find the user's location. This error occurs when the user declines the location request or has location servives turned off.
NSString * errorString = @"Unable to determine your current location.";
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error Locating" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
[locationManager stopUpdatingLocation];
}
- (void)dealloc { #warning dont forget this :) }
@end
Hope this help.
I think is contrary to Apple Guidelines to force updates. Apple says geo-update will occur automatically, but at un unknown time.
精彩评论