ユーザーの座標を取得したいのですが、ユーザーがアプリを起動したら、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);
}
問題は両方latitude
であり、longitdute
関数は 0.000 を返しています。ここで何が欠けていますか? iOS6.1向けに開発しています。