我想获取用户的坐标,一旦用户启动应用程序,它应该初始化 GPS 坐标。我遵循了本教程: http: //www.iosdevnotes.com/2011/10/ios-corelocation-tutorial/
我创建了一个名为 CurrentLocationWithGPS 的类
这是标题:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@interface CurrentLocationWithGPS : NSObject<CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
- (void) getLocations;
- (Float32) latitude;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLLocation *currentLocation;
@end
这是实现:
#import "CurrentLocationWithGPS.h"
@implementation CurrentLocationWithGPS
@synthesize locationManager, currentLocation;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.currentLocation = newLocation;
if(newLocation.horizontalAccuracy <= 100.0f) { [locationManager stopUpdatingLocation]; }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if(error.code == kCLErrorDenied) {
[locationManager stopUpdatingLocation];
} else if(error.code == kCLErrorLocationUnknown) {
// retry
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error retrieving location"
message:[error description]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}
- (void) getLocations {
NSLog(@"GPS Location is initialising...");
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
NSLog(@"GPS Location is initialised...");
}
- (Float32) latitude {
return currentLocation.coordinate.latitude;
}
- (Float32) longitude {
return currentLocation.coordinate.longitude;
}
@end
我在一个单独的线程中调用 getLocations 函数,这样它就不会阻塞其他任何东西。这是我从另一个类中调用它的方式:
- (void)viewDidLoad
{
[super viewDidLoad];
NSThread *myThread =[[NSThread alloc]initWithTarget:self selector:@selector(locationSet) object:nil];
[myThread start];
}
- (void) locationSet {
CurrentLocationWithGPS *locationFind = [[CurrentLocationWithGPS alloc] init];
locationFind.getLocations;
NSLog(@"latitude is %f", locationFind.latitude);
}
现在问题出在两个函数都返回 0.000 latitude
,longitdute
我在这里缺少什么?我正在为 iOS6.1 开发。