1

我是 iOS 编程新手,并试图获取我当前的位置。我的主要应用程序代表是这样的,

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@class AWSViewController;

@interface AWSAppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) AWSViewController *viewController;
@property (strong, nonatomic) UINavigationController *navController;
@property (strong, nonatomic) NSMutableArray *cities;

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

@end

在实现中,我有这两种方法,我从(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

我可以在控制台上看到“开始获取位置”字样,之后我看不到任何其他内容。

-(void)getCurrentLocation {

    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    locationManager.distanceFilter = 500;
    [locationManager startUpdatingLocation];
    NSLog(@"Started to get locations");
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *location = [locations lastObject];
    NSLog(@"Got Location");
    NSLog(@"latitude %+.6f, longitude %+.6f\n", location.coordinate.latitude, location.coordinate.longitude);
}

我在这里做错了什么?谢谢

4

3 回答 3

3

一旦代码退出您的getCurrentLocation方法,您的位置管理器就会超出范围。制作一个位置管理器 ivar,以便它留在周围。

@interface AWSAppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
}



-(void)getCurrentLocation {
    locationManager = [[CLLocationManager alloc] init];
    // etc
}
于 2013-08-29T14:23:20.090 回答
1

我修好了:D

我的 locationManager 对象 - 我实例化了它,但你没有保留它,所以它会立即消失在一阵烟雾中

@property (strong, nonatomic) CLLocationManager *locationManager;

然后,

-(void)getCurrentLocation {

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    self.locationManager.distanceFilter = 5;
    [self.locationManager startUpdatingLocation];
    NSLog(@"Started to get locations");
}

现在它完美地工作了:D

于 2013-08-29T13:56:49.447 回答
0

您的位置管理器是否启用?核实:

if(locationManager.locationServicesEnabled == NO){
  //go to settings>location services
}

如果事情变糟了,方法

locationManager:didFailWithError:

被称为而不是

locationManager:didUpdateLocations

所以,请实施它:

- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error {
    NSLog(@"error%@",error);
}
于 2013-08-29T12:47:55.930 回答