gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:18:37 25 4
gpt4 key购买 nike

我已经知道如何使用 CLLocationManager,所以我可以用委托(delegate)等困难的方式来完成它。

但我想要一个方便的方法,只需获取当前位置一次,然后阻塞直到获得结果。

最佳答案

我所做的是实现一个单例类来管理来自核心位置的更新。要访问我的当前位置,我执行 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

关于iphone - 获取 iPhone 当前位置的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/459355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com