Mic*_*are 22 iphone core-location
我已经知道如何使用CLLocationManager,所以我可以用代表和所有这些来完成它.
但我希望有一个方便的方法,只需获取当前位置一次,然后阻塞直到获得结果.
Bra*_*Guy 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
}
Run Code Online (Sandbox Code Playgroud)
但是,正如已经指出的那样,阻塞主线程可能不是一个好主意,但是当你正在构建一些东西时,这可能是一个很好的跳跃点.您还会注意到我编写的类检查位置更新的时间戳并忽略任何旧的,以防止从核心位置获取过时数据的问题.
这是我写的单身课程.请注意,边缘有点粗糙:
#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
Run Code Online (Sandbox Code Playgroud)
没有这样的便利,你不应该创建自己的."阻塞直到它得到结果"是像iPhone这样的设备上非常糟糕的编程习惯.检索位置可能需要几秒钟; 你不应该让你的用户像这样等待,代表们确保他们不这样做.
除非您自己编写代码,否则不存在“方便的方法”,但您仍然需要在使用的任何自定义代码中实现委托方法以使事情变得“方便”。
委托模式的存在是有原因的,并且由于委托是 Objective-C 的重要组成部分,我建议您熟悉它们。
归档时间: |
|
查看次数: |
30872 次 |
最近记录: |