获取iPhone当前位置的最简单方法是什么?

时间:2009-01-19 22:00:09

标签: iphone core-location

我已经知道如何使用CLLocationManager,所以我可以用代表和所有这些来完成它。

但是我希望有一个方便的方法,只需获取当前位置一次,并阻塞直到获得结果。

5 个答案:

答案 0 :(得分:45)

我所做的是实现一个单例类来管理核心位置的更新。要访问我当前的位置,我执行CLLocation *myLocation = [[LocationManager sharedInstance] currentLocation];如果您想阻止主线程,您可以执行以下操作:

while ([[LocationManager sharedInstance] locationKnown] == NO){
   //blocking here
   //do stuff here, dont forget to have some kind of timeout to get out of this blocked    //state
}

然而,正如已经指出的那样,阻止主线程可能不是一个好主意,但这可能是一个很好的跳跃点,因为你正在构建一些东西。您还会注意到我编写的类会检查位置更新的时间戳,并忽略任何旧的,以防止从核心位置获取过时数据的问题。

这是我写的单身人士课程。请注意,边缘有点粗糙:

#import <CoreLocation/CoreLocation.h>
#import <Foundation/Foundation.h>

@interface  LocationController : NSObject <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
    CLLocation *currentLocation;
}

+ (LocationController *)sharedInstance;

-(void) start;
-(void) stop;
-(BOOL) locationKnown;

@property (nonatomic, retain) CLLocation *currentLocation;

@end
@implementation LocationController

@synthesize currentLocation;

static LocationController *sharedInstance;

+ (LocationController *)sharedInstance {
    @synchronized(self) {
        if (!sharedInstance)
            sharedInstance=[[LocationController alloc] init];       
    }
    return sharedInstance;
}

+(id)alloc {
    @synchronized(self) {
        NSAssert(sharedInstance == nil, @"Attempted to allocate a second instance of a singleton LocationController.");
        sharedInstance = [super alloc];
    }
    return sharedInstance;
}

-(id) init {
    if (self = [super init]) {
        self.currentLocation = [[CLLocation alloc] init];
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        [self start];
    }
    return self;
}

-(void) start {
    [locationManager startUpdatingLocation];
}

-(void) stop {
    [locationManager stopUpdatingLocation];
}

-(BOOL) locationKnown { 
     if (round(currentLocation.speed) == -1) return NO; else return YES; 
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    //if the time interval returned from core location is more than two minutes we ignore it because it might be from an old session
    if ( abs([newLocation.timestamp timeIntervalSinceDate: [NSDate date]]) < 120) {     
        self.currentLocation = newLocation;
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    UIAlertView *alert;
    alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[error description] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

-(void) dealloc {
    [locationManager release];
    [currentLocation release];
    [super dealloc];
}

@end

答案 1 :(得分:7)

没有这样的便利,你不应该创建自己的。 “阻止它获得结果”是像iPhone这样的设备上的非常糟糕的编程习惯。检索位置可能需要几秒钟;你不应该让你的用户这样等待,代表们确保他们不这样做。

答案 2 :(得分:4)

除非您自己编写代码,否则没有“便捷方法”,但您仍需要在用于使事情变得“方便”的任何自定义代码中实现委托方法。

委托模式是有原因的,因为代表是Objective-C的重要组成部分,我建议你对它们感到满意。

答案 3 :(得分:0)

我很欣赏布拉德史密斯的回答。实现它我发现他使用的其中一种方法从iOS6开始就被弃用了。要编写适用于iOS5和iOS6的代码,请使用以下命令:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    if (abs([[locations lastObject] timeIntervalSinceDate:[NSDate date]]) < 120) {
        [self setCurrentLocation:[locations lastObject]];
    }
}

// Backward compatibility with iOS5.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSArray *locations = [NSArray arrayWithObjects:oldLocation, newLocation, nil];
    [self locationManager:manager didUpdateLocations:locations];
}

答案 4 :(得分:0)

我简化并组合了多个答案,只有在有效的情况下才会更新位置。

它也适用于OSX以及iOS。

这假设用户突然想要当前位置的用例。如果在此示例中花费超过100毫秒,则将其视为错误。 (假设GPS IC&amp; | Wifi(Apple的Skyhook克隆版)已经启动并且已经有了很好的解决方案。)

#import "LocationManager.h"

// wait up to 100 ms
CLLocation *location = [LocationManager currentLocationByWaitingUpToMilliseconds:100];
if (!location) {
    NSLog(@"no location :(");
    return; 
}
// location is good, yay

https://gist.github.com/6972228