将GPS集成到我的应用程序中

时间:2012-01-15 15:44:31

标签: iphone objective-c ios core-location

我正在关注tutorial将GPS集成到我的应用程序中。我想在Latitude方法中显示LongitudeviewDidLoad值。根据教程,他们从另一种方法显示它。但是我需要它显示在viewDidLoad中。如何修改以下代码以在viewDidLoad

中显示它

HelloThereController.h视图控制器

#import "MyCLController.h"

@interface HelloThereViewController : UIViewController <MyCLControllerDelegate> {
    MyCLController *locationController;
}

- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;

@end

HelloThereController.m视图控制器

#import "HelloThereViewController.h"

@implementation HelloThereViewController

- (void)viewDidLoad {
    locationController = [[MyCLController alloc] init];
    locationController.delegate = self;
    [locationController.locationManager startUpdatingLocation];

    //I need to print the latitude and logitude values here..
}

My MyCLController.h class

@protocol MyCLControllerDelegate 
@required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
@end

@interface MyCLController : NSObject  {
    CLLocationManager *locationManager;
    id delegate;
}

@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, assign) id  delegate;

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation;

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error;

@end 

My MyCLController.m class

#import "MyCLController.h"

@implementation MyCLController

@synthesize locationManager;
@synthesize delegate;

- (id) init {
    self = [super init];
    if (self != nil) {
        self.locationManager = [[[CLLocationManager alloc] init] autorelease];
        self.locationManager.delegate = self; 
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
         fromLocation:(CLLocation *)oldLocation
{
    [self.delegate locationUpdate:newLocation];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    [self.delegate locationError:error];
}

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

@end

2 个答案:

答案 0 :(得分:2)

如果此视图控制器在应用加载后立即加载,则不能。 位置管理员需要时间来获取gps更新。

您需要显示一些ui组件,让用户知道您正在获取该位置,例如UIActivityIndi​​catorView,并设置另一种方法来显示坐标。

答案 1 :(得分:0)

通常,您可以加快处理过程,从而牺牲一些准确性来设置desiredAccuracy属性。根据文档,值为:

kCLLocationAccuracyBestForNavigation
kCLLocationAccuracyBest
kCLLocationAccuracyNearestTenMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyKilometer
kCLLocationAccuracyThreeKilometers

无论如何,您对第一个位置感兴趣,所以仍然根据文档:

  

请求高精度位置数据时,该位置提供的初始事件   服务可能没有您要求的准确性。 位置服务提供初始服务   事件尽快。然后继续确定准确的位置   当有数据可用时,您已根据需要请求并提供其他活动。

您可以尝试在AppDelegate didFinishLaunchingWithOptions中启动位置管理器,以便在视图出现之前有更多时间。正如Frederick Cheung所说,locationManager.location可以是nil,因此最好在位置管理器委托中进行操作。